使用BigIntegers作为Java中while循环的条件

时间:2011-02-14 14:47:08

标签: java

我想在while循环条件中使用一个大整数值,但这不起作用。

import java.util.Scanner;
import java.util.StringTokenizer;
public class NiceProbelm2 {
public static void main(String[]args){
    Scanner input = new Scanner(System.in);
    String number = input.nextLine();
    StringTokenizer st = new StringTokenizer(number);
    BigInteger base = null;
    int power=0;
    while (st.hasMoreTokens()) {
          String token1 = st.nextToken();
          String token2 = st.nextToken();
          base = new BigInteger(token1);
          power = Integer.parseInt(token2);


        }

        BigInteger result = base.pow(power);
        //long fresult = (long)result;
        BigInteger div = new BigInteger("10");
        System.out.println(result);
        BigInteger sum=null;
     //NOt working while(result.compareTo(new BigInteger("0")) > 10 )
                    {
        BigInteger digit = result.mod(div);
        result = result.divide(div);
        sum = sum.add(digit);

    }
     System.out.println(sum);
}

}

4 个答案:

答案 0 :(得分:7)

你永远不应该将compareTo()的返回值与0以外的任何值进行比较。(BigInteger.compareTo()更具体一些,但仍适用相同的规则)

您可以检查它是否大于0,小于0或等于0.只有这3条信息才真正相关。实际值(如果它返回1或10或100)无关紧要。

答案 1 :(得分:1)

你必须使用这个条件:

result.compareTo(BigInteger.ZERO) > 0

答案 2 :(得分:1)

我认为你之前的解决方案存在问题,因为你的累加器没有被初始化,你有一个被抛出的空指针。以下代码生成您要查找的结果:

        BigInteger result = base.pow(power);
        BigInteger div = new BigInteger("10");
        System.out.println(result);
//The following line is different, initialize the sum before using it.
        BigInteger sum = BigInteger.ZERO;
        while(!BigInteger.ZERO.equals(result)) {
            BigInteger digit = result.mod(div);
            result = result.divide(div);
            sum = sum.add(digit);
        }
        System.out.println(sum);

我还想指出BigInteger有一个方法可以提供单个除法的商和余数,这比单独执行它们更有效,并且BigInteger有一个“valueOf”方法,所以你可以使用数字文字而不是字符串:

    BigInteger result = base.pow(power);
    BigInteger div = BigInteger.valueOf(10);
    System.out.println(result);

    //Initialize the sum to zero
    BigInteger sum = BigInteger.ZERO;        
    //While the result has a non-zero decimal digit
    while(!BigInteger.ZERO.equals(result)) {
        //this divides by ten (first element),
        //and calculates the remainder (second element)
        BigInteger[] lastDigit = result.divideAndRemainder(div);
        result = lastDigit[0];
        sum = sum.add(lastDigit[1]);

    }
    System.out.println(sum);

答案 3 :(得分:0)

看起来你想要写while (result != 0),你会写得像 while (result.compareTo(BigInteger.ZERO) != 0)

此外,您需要将sum初始化为BigInteger.ZERO