Title Description
Enter the number n, in order to print out a decimal from 1 to the maximum n-bit number. For example, input 3, then print out up to a maximum of 1, 2, 3 digits, ie 999.
Ideas analysis
- To take into account the problem of large numbers, we ask whether the n-digit integer, there is no obvious limitations of size n, we can use the string to print the number of bits n
- We need to do two things:
- In the digital representation of the analog +1 string, the string plus one operation, add a note of the time is stopped, i.e., when the most significant bit + 1, if a carry is stopped plus 1, for example: 1 + 999
- n print string representation of the number, digital printing character array formation, not the time to pay attention to when faced with '0' to start printing
Test Case
- Function test (input 1,2,3 ......)
- Special test input (input 0, -1)
Java code
public class Offer17 {
public static void main(String[] args) {
System.out.println("功能测试--->");
test1();
System.out.println("特殊值测试--->");
test2();
}
public static void print1ToMaxOfNDigits(int n) {
Solution1(n);
}
/**
* 用模拟加1 的方法
*
* @param n
*/
private static void Solution1(int n) {
if (n <= 0) {
throw new IllegalArgumentException("参数非法");
}
char[] number = new char[n];
Arrays.fill(number, '0');// 全部初始化为为'0'
while (!increment(number)) {
printCharNumber(number);
}
}
/**
* 对字符串进行加一操作,注意停止加一的时机,即当最高位+1时,如果产生进位,则停止加1 ,比如:999+1
*
* @param number
* @return
*/
private static boolean increment(char[] number) {
boolean isOverflow = false; // 判断最高位是否产生进位,停止+1的条件
int nTakeOver = 0; // 产生的进位
// 数组从后往前遍历,数组后面的位表示数值的低位
for (int i = number.length - 1; i >= 0; i--) {
int nSum = (number[i] - '0') + nTakeOver;
if (i == number.length - 1) {
nSum++;
}
if (nSum >= 10) {
if (i == 0) {// 最高位
isOverflow = true;
} else {
nSum -= 10;
nTakeOver = 1;
number[i] = (char) ('0' + nSum);
}
} else {
number[i] = (char) ('0' + nSum);
break;
}
}
return isOverflow;
}
/**
* 打印字符数组形成的数字,注意当遇到不是'0'的时候才开始打印
*/
private static void printCharNumber(char[] number) {
boolean isBeginning0 = true;
for (int i = 0; i < number.length; i++) {
if (isBeginning0 && (number[i] - '0') != 0) {
isBeginning0 = false;
}
if (!isBeginning0) {
System.out.print(number[i]);
}
}
System.out.println();
}
private static void test1() {
System.out.println("2---->");
print1ToMaxOfNDigits(2);
}
private static void test2() {
System.out.println("-1---->");
print1ToMaxOfNDigits(-1);
System.out.println("0---->");
print1ToMaxOfNDigits(0);
}
}