【问题标题】:Add two Integers up to 50 digits将两个整数相加,最多 50 位
【发布时间】:2014-06-23 10:47:39
【问题描述】:

这是真正的问题:

编写一个交互式程序,将两个整数相加,每个整数最多 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;
    }
}

【问题讨论】:

  • 请更具体。您的问题非常模糊,将导致关闭它。
  • 你不能用String然后转换成BigInteger来处理吗???
  • @StephenFrancis 你试过tempBigInteger = tempBigInteger.divide(BigInteger.TEN)吗?
  • @StephenFrancis digits[49-i] = tempBigInteger.mod(BigInteger.TEN).longValue();?
  • 我认为作业应该自己尝试。不是众包的。 ;-)

标签: java arrays integer add


【解决方案1】:

输入不超过 20 位,但必须使用 50 位。

这是因为您正在使用x = s.nextLong(),它试图将输入转换为long。最大长值是9223372036854775807,它远不接近 50 位。您需要将输入作为字符串获取,然后将其转换为您的 int[]

'integerToDigits' 方法生成两个数组,但我无法理清如何使用它们并将它们添加到 main 方法中。

在将数字数组相加方面,您可以使用我们很早就在学校学习的相同过程。

  • 添加单位,然后结转任何十位。
  • 将十位相加并结转任何数百位。
  • 添加数百并结转任何数千。
  • ...

这个过程可以迭代添加每个数量级以及前一个数量级的结转。

希望这些提示可以为您提供解决问题的方法。

如果您确实需要解决方案,I've produced one here 似乎可以满足您的要求。 (虽然显然不在ideone中)

【讨论】:

  • 非常感谢...我会尝试一下,然后将其与您的解决方案进行比较。
【解决方案2】:

如果“将整数表示为数字数组”是建议而非要求,则使用 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,我会将其存储为字符串。

【讨论】:

  • 谢谢,但必须将它们表示为数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 2016-02-22
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多