Skip to content

Commit 017fb29

Browse files
committed
print1ToMaxOfNDigits
1 parent 893ccea commit 017fb29

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package problem12;
2+
3+
/**
4+
* 打印1到最大的n位数,如输入3,则打印1,2,3,。。。。,999
5+
* 思路:大数,如果面试题是关于n位的整数并且没有限定n的取值范围,或者输入任意大小的整数,则要考虑用
6+
* 字符串来模拟大数问题
7+
* Created by bjyangrubing on 2016/8/16.
8+
*/
9+
public class Print1ToMaxOfNDigits
10+
{
11+
public void print1ToMaxOfNDigits(int n)
12+
{
13+
if (n <= 0)
14+
return;
15+
char[] numbers = new char[n];
16+
//初始化numbers为0
17+
for (int i = 0; i < numbers.length; i++)
18+
{
19+
numbers[i] = '0';
20+
}
21+
while (!increment(numbers))//如果没有overFlow
22+
{
23+
printNumbers(numbers);
24+
}
25+
26+
}
27+
28+
/**
29+
* 打印的函数
30+
* @param numbers
31+
*/
32+
private void printNumbers(char[] numbers)
33+
{
34+
boolean isBeginning0 = true;
35+
for (int i = 0; i < numbers.length; i++)
36+
{
37+
if (numbers[i] != '0')
38+
isBeginning0 = false;
39+
if (!isBeginning0)
40+
{
41+
System.out.print(numbers[i]);
42+
}
43+
}
44+
45+
System.out.println();
46+
}
47+
48+
private boolean increment(char[] numbers)
49+
{
50+
boolean isOverFlow = false;
51+
int nTakeOver = 0;//第n位的进位,有则为0
52+
int nLength = numbers.length;
53+
for (int i = nLength - 1; i >= 0; i--)
54+
{
55+
int nSum = numbers[i] - '0' + nTakeOver;//第n位的和
56+
if (i == nLength - 1)//如果是个位,则+1
57+
nSum += 1;
58+
if (nSum >= 10)//加完以后大于10
59+
{//如果末位的数值大于10
60+
if (i == 0)
61+
{//如果是最高位
62+
isOverFlow = true;
63+
}
64+
else
65+
{//否则设置为有进位,并且把值设置为'0'
66+
nSum -= 10;
67+
nTakeOver = 1;
68+
numbers[i] = (char) ('0' + nSum);
69+
}
70+
}
71+
else
72+
{//否则,直接赋值并且break
73+
numbers[i] = (char) (nSum + '0');
74+
break;
75+
}
76+
}
77+
return isOverFlow;
78+
}
79+
80+
public static void main(String[] args)
81+
{
82+
Print1ToMaxOfNDigits p = new Print1ToMaxOfNDigits();
83+
p.print1ToMaxOfNDigits(3);
84+
}
85+
86+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package problem12;
2+
3+
import org.junit.Test;
4+
5+
/**
6+
* Created by bjyangrubing on 2016/8/16.
7+
*/
8+
public class Print1ToMaxOfNDigitsTest
9+
{
10+
@Test
11+
public void test()
12+
{
13+
Print1ToMaxOfNDigits p = new Print1ToMaxOfNDigits();
14+
p.print1ToMaxOfNDigits(3);
15+
}
16+
}

0 commit comments

Comments
 (0)