2014-12-04 41 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(); 
} 
相關問題