2014-12-04 74 views
-6

我有一个严重的问题。我需要得到一个数字说获取超过30位数字输入的数据类型

123454466666666666666665454545454454544598989899545455454222222222222222 

并给出该数字的总数。我想了很久。我无法得到答案。问题是我不知道使用哪种数据类型。我试了很久。它只接受18位数字。我已经通过BigInteger。但我无法对它进行算术运算。所以帮我解决这个问题..

+3

请告诉我一个“总该数字的”。只是所有数字的总和?然后你应该使用字符串。 – libik 2014-12-04 12:58:25

+0

尝试字符串。解析每个字符的整数并添加全部。 – 2014-12-04 12:59:40

+0

@DarshanLila BigInteger的功能非常强大。 – Sirko 2014-12-04 13:00:10

回答

2

您可以从下面的代码中获得结果。

String string = "123454466666666666666665454545454454544598989899545455454222222222222222"; 
int count = 0; 
for (int i = 0; i < string.length(); i++) { 
    count += Integer.parseInt(String.valueOf(string.charAt(i))); 
} 
System.out.println(count); 
+1

谢谢你ashok ..它为我工作.. – Techieee 2014-12-04 13:04:09

3
1.Get it as a string 
2.get length of it. 
3.Loop through each character of it. 
4.check if the character is a number. 
5.If yes parse it to int. 
6.Add all numbers together in the loop 

OR 

Use BigDecimal 
0

的BigInteger不支持的方法,如加/乘等见this了解详情。

BigInteger operand1 = new BigInteger("123454466666666666666665454545454454544598989899545455454222222222222222"); 
    BigInteger operand2 = new BigInteger("123454466666666666666665454545454454544598989899545455454222222222222222"); 
    System.out.println(operand1.add(operand2)); 
    System.out.println(operand1.subtract(operand2)); 
    System.out.println(operand1.multiply(operand2)); 
    System.out.println(operand1.divide(operand2)); 
2

只要使用它作为String。这是完成手头任务的最简单方法。

public class Test022 { 
    public static void main(String[] args) { 
     String s = "123454466666666666666665454545454454544598989899545455454222222222222222"; 
     int sum = 0; 
     for (int i=0; i<s.length(); i++){ 
      sum += s.charAt(i) - '0'; 
     } 
     System.out.println(sum); 
    } 
} 
0

我可以建议使用此代码和数字作为字符串

/** 
* Adds two non-negative integers represented as string of digits. 
* 
* @exception NumberFormatException if either argument contains anything other 
*   than base-10 digits. 
*/ 
public static String add(String addend1, String addend2) { 
    StringBuilder buf = new StringBuilder(); 
    for (int i1 = addend1.length() - 1, i2 = addend2.length() - 1, carry = 0; 
      (i1 >= 0 && i2 >= 0) || carry != 0; 
      i1--, i2--) { 
     int digit1 = i1 < 0 ? 0 : 
        Integer.parseInt(Character.toString(addend1.charAt(i1))); 
     int digit2 = i2 < 0 ? 0 : 
        Integer.parseInt(Character.toString(addend2.charAt(i2))); 

     int digit = digit1 + digit2 + carry; 
     if (digit > 9) { 
      carry = 1; 
      digit -= 10; 
     } else { 
      carry = 0; 
     } 

     buf.append(digit); 
    } 
    return buf.reverse().toString(); 
}