剑指 Offer 17. 打印从1到最大的n位数
题目:
思路:
主要是考察大数的加法和打印,有两种思路,推荐递归(从char[0]到char[length-1] 从0到9即可。然后再if条件处进行打印即可)
leetcode这道题竟然返回int[],真的垃圾,还尼玛标记简单。
class Solution {
public int[] printNumbers(int n) {
char[] s = new char[n];
int temp = n;
int length = 1;
while (temp > 0) {
length *= 10;
temp--;
}
int[] ints = new int[length-1];
for (int i = 0; i < s.length; i++) {
s[i] = '0';
}
// 每次都进入一个循环,从个位开始计算,否则不知道要写多少fori
int count = 0;
while(!increase(s)){
ints[count] = Integer.parseInt(String.copyValueOf(s));
count++;
}
return ints;
}
// 这个char[] 计算+1的方法很讨巧,当个位>= 10时,高位每次+1
private boolean increase(char[] s) {
boolean carry = false;
int takeover = 0;
for (int i = s.length - 1; i >= 0; i--) {
int num = s[i] - '0' + takeover;
if (i == s.length - 1) {
num++;
}
if (num >= 10) {
if (i == 0) {
carry = true;
} else {
num -= 10;
s[i] = (char) (num + '0');
takeover = 1;
}
} else {
s[i] = (char) (num + '0');
break;
}
}
return carry;
}
}
递归+1的代码:
class Solution {
private int a = 0;
public int[] printNumbers(int n) {
char[] s = new char[n];
int temp = n;
int length = 1;
// 计算n位数的长度
while (temp > 0) {
length *= 10;
temp--;
}
int[] ints = new int[length];
for (int i = 0; i < ints.length; i++) {
ints[i] = '0';
}
// 递归计算,从各位道最高位开始递归,从0到9
increase(s, ints, s.length,-1);
// 首位为0,不符合条件。想不出其他方法了。如果不用返回数组,不打印0即可
int[] ints1 = new int[ints.length - 1];
for (int i = 1; i < ints.length; i++) {
ints1[i - 1] = ints[i];
}
return ints1;
}
private void increase(char[] s, int[] ints, int length,int index) {
if (index == length -1) {
if(a > ints.length) return;
ints[a] = Integer.parseInt(String.copyValueOf(s));
a++;
return;
}
for (int i = 0; i < 10; i++) {
s[index+1] = (char) (i + '0');
increase(s, ints, length,index+1);
}
}
}