剑指offer面试题12 使用BigInteger来实现 打印1到最大的n位数

来源:互联网 发布:java 接口变量 编辑:程序博客网 时间:2024/04/30 12:29
/**
* 注意事项:
* 1.n位数为无穷大时怎么办,首先int表示不了。是否可选BigInteger
* 2.n为负数时,异常错误
* 3.循环输出时,分界值判断位数
* 步骤:
* 1.判断n是否为负数,输出异常(可用一个全局变量);
* 2.求出最大值为max=9e(n)+9e(n-1)……+9e(0)
* 3.放不下怎么办?

* @param n 位数
* @return
*/
    boolean invalidInput=false;
public String printMaxOfN(int n) {
invalidInput=false;
if(n<0)
{
invalidInput=true;
return null;

}
BigInteger bigInteger1=BigInteger.valueOf(n);

System.out.println(bigInteger1.toString());

BigInteger result=BigInteger.valueOf(1);
BigInteger resultLast=BigInteger.valueOf(0);
for(BigInteger bigInteger=BigInteger.valueOf(0);bigInteger.compareTo(bigInteger1)==-1;bigInteger=bigInteger.add(BigInteger.ONE))
{
System.out.println(bigInteger.toString()+"********");

for(BigInteger bigInteger2=BigInteger.valueOf(1);bigInteger2.compareTo(bigInteger)<=0;bigInteger2=bigInteger2.add(BigInteger.ONE))
{

result=result.multiply(BigInteger.valueOf(10));
System.out.println(result.toString()+"+++++++");

}
resultLast=resultLast.add(result.multiply(BigInteger.valueOf(9)));
result=BigInteger.valueOf(1);
// bigInteger.add(BigInteger.valueOf((long) 9ei));

}


// for(int i=0;i<=n;i++)
// {
// for(int j=0;j<=i;j++)
// {
//
//
// }
//// bigInteger.add(BigInteger.valueOf((long) 9ei));
//
// }

return resultLast.toString();




}
}
0 0