[英]Add two Integers up to 50 digits
這是實際的問題:
編寫一個交互式程序,將兩個不超過50個數字的整數相加(將整數表示為數字數組)。
這是一個作業問題,使用的語言是Java。 我走的很遠,但我認為還差得遠。
1.輸入的數字不能超過20位,而必須使用50位。
2.“ integerToDigits”方法產生兩個數組,但是我無法弄清楚如何使用它們並將它們添加到main方法中。
請幫助。
package One;
import java.util.Scanner;
public class AddInt {
public static void main(String[] args) {
Long x,y;
Long a[] = new Long[50];
Long b[] = new Long[50];
System.out.println("Please enter two numbers which have no more than 50 digits: ");
Scanner s = new Scanner(System.in);
x = s.nextLong();
y = s.nextLong();
System.out.println(x+ "and "+y);
integerToDigits(x);
integerToDigits(y);
}
public static Long[] integerToDigits(Long n){
Long digits[] = new Long[50];
Long temp = n;
for(int i = 0; i < 50; i++){
digits[49-i] = temp % 10;
temp /= 10;
}
return digits;
}
}
如果“不是將整數表示為數字數組”是建議,而不是要求,那么使用BigInteger的解決方案將類似於:
// read numbers from input
// store first value as String "firstNumber"
// store second value as String "secondNumber"
BigInteger a = new BigInteger(firstNumber);
BigInteger b = new BigInteger(secondNumber);
BigInteger result = a.add(b);
System.out.println("Result is " + result.toString());
如果“將整數表示為數字數組”是一個必要條件,那么這是一個愚蠢的任務:)沒有人會存儲這樣的整數。 最壞的情況是,如果不允許BigInteger,我會將其存儲為String。
輸入的位數不超過20位,而必須使用50位。
這是因為您使用的x = s.nextLong()
試圖將輸入轉換為long
。 最大長值是9223372036854775807
,距離50位數字不遠。 您需要以字符串形式獲取輸入,然后將其隱式化為int[]
“ integerToDigits”方法產生兩個數組,但我無法弄清楚如何使用它們並將它們添加到main方法中。
就將數字數組相加而言,您可以使用我們在學校很早就學習過的相同過程。
可以重復此過程,將每個數量級與前一個的結轉相加。
希望這些技巧能給您解決問題的方法。
如果您確實想要一種解決方案,那么我在這里提供了一個可以按照您的要求工作的解決方案。 (盡管顯然不在ideone中)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.