Java 添加非常大的数字的输出没有达到预期

Java 添加非常大的数字的输出没有达到预期,java,string,Java,String,给定两个数字作为输入,返回这些数字的总和。请注意,数字可能非常大,因此作为字符串提供 注意:如果不使用BigInteger类,我必须添加它们 #Sample Input #1 add("2354725234782357","9999999999999999999999999988888888888") #Sample Output #1 10000000000000000000002354714123671245 #Sample Input #2 add("1600","213")

给定两个数字作为输入,返回这些数字的总和。请注意,数字可能非常大,因此作为字符串提供

注意:如果不使用BigInteger类,我必须添加它们

#Sample Input #1

add("2354725234782357","9999999999999999999999999988888888888")

#Sample Output #1

10000000000000000000002354714123671245

#Sample Input #2

add("1600","213")

#Sample Output #2

1813
MyApproach

由于这些数字非常大,我无法获得输出。有谁能指导我做错了什么以及如何添加这些数字

原始代码:

public String add(String str1, String str2) {
    long number1 = Long.parseLong(str1);
    long number2 = Long.parseLong(str2);
    number1 = number1 + number2;
    return "" + number1;
}
参数:

'2354725234782357'9999999999999999999999998888888'
实际产量:

null
预期产出:

100000000000000000002354714123671245

编辑:

public String add(String str1, String str2) {
    long number1 = Long.parseLong(str1);
    long number2 = Long.parseLong(str2);
    number1 = number1 + number2;
    return "" + number1;
}
根据MC皇帝的建议,我知道了如何在不使用任何BigInteger的情况下添加非常大的数字

Below is the code.

public String add(String a, String b) 
{

     String result = "";
    if(a.length()>b.length())
    {
        int p=a.length()-b.length();
        for(int i=0;i<p;i++)
         {
          b="0"+b;
         } 
    }
    if(b.length()>a.length())
    {
        int p=b.length()-a.length();
        for(int i=0;i<p;i++)
         {
           a="0"+a;
         } 
    }
    if(a.length()==b.length()) 
    {    


       int carry = 0;
      for (int i = a.length() - 1; i >= 0; i--) 
      {

         int digitA = a.charAt(i) - 48;
         int digitB = b.charAt(i) - 48;


         int resultingNumber = digitA + digitB + carry;
         if (resultingNumber >= 10) 
         {

            result = (resultingNumber % 10) + result;
             carry = 1;
         }
         else
        {
         result = resultingNumber + result;
         carry = 0;
        }
      }
      if (carry > 0)
     {
       result = carry + result;
     }

   }
   return result;
 }
}    
下面是代码。
公共字符串添加(字符串a、字符串b)
{
字符串结果=”;
如果(a.length()>b.length())
{
int p=a.length()-b.length();
对于(int i=0;ia.length())
{
int p=b.length()-a.length();
对于(int i=0;i=0;i--)
{
int digitA=a.charAt(i)-48;
int digib=b.charAt(i)-48;
int resultingNumber=digitA+digib+carry;
如果(结果编号>=10)
{
结果=(结果编号%10)+结果;
进位=1;
}
其他的
{
结果=结果编号+结果;
进位=0;
}
}
如果(进位>0)
{
结果=进位+结果;
}
}
返回结果;
}
}    
试试这个

String fix(String s, int size) {
    int len = size - s.length();
    if (len <= 0) return s;
    return String.format("%0" + len + "d%s", 0, s);
}

public String add(String a, String b) {
    int len = Math.max(a.length(), b.length());
    a = fix(a, len);
    b = fix(b, len);
    StringBuilder r = new StringBuilder();
    int carry = 0;
    for (int i = len - 1; i >= 0; --i) {
        int sum = carry + a.charAt(i) - '0' + b.charAt(i) - '0';
        r.append((char)(sum % 10 + '0'));
        carry = sum / 10;
    }
    if (carry > 0)
        r.append((char)(carry + '0'));
    return r.reverse().toString();
}
字符串修复(字符串s,整数大小){
int len=尺寸-s.长度();
如果(len=0;--i){
整数和=进位+a.charAt(i)-“0”+b.charAt(i)-“0”;
r、 追加((字符)(总和%10+0');
进位=总和/10;
}
如果(进位>0)
r、 追加((字符)(进位+0');
返回r.reverse().toString();
}

这里是相同的东西,没有任何大整数。注释掉代码进行解释

/**
 * Created by ankur on 10-12-2015.
 *
 * add two very large number without big integer
 */
public class BigStringAddition {

    public static void main(String[] args){

        System.out.println(StringAddition("2354725234782357","9999999999999999999999999988888888888"));

    }

    /*
    function to return the result
     */
    public static String StringAddition(String first, String second){
        StringBuilder bufferRes = new StringBuilder();

        /*
        looping through the index for the break point or carry and adding the result
         */
        for (int index1 = first.length() - 1, index2 = second.length() - 1, carry = 0; index1 >= 0 || index2 >= 0 || carry != 0; index1--, index2--){

            // get the digit from the back and convert it into integer
            int dig1 = index1 < 0 ? 0 : Integer.parseInt(Character.toString(first.charAt(index1)));

            int dig2 = index2 < 0 ? 0 : Integer.parseInt(Character.toString(second.charAt(index2)));

            // add both the digit and carry

            int resDig = dig1 + dig2 + carry;

            // if the digit is greater than > 9 carry will be 1

            if (resDig > 9){
                carry = 1;
                resDig -= 10;
            }else{
                carry = 0;
            }

            bufferRes.append(resDig);

        }


        return bufferRes.reverse().toString();
    }
}

Ideone Link:

您应该知道,long默认有64位,其1用于符号,因此最大值为
263-1
,或
9223372036854775807
。作业告诉你这些数字可能非常大,所以我猜这些数字可能会超过最大值

  • Long.parseDouble(String)
    不存在,我想你的意思是
    Long.parseLong(String)
  • 正如您所说,您的代码不会输出
    null
    ,而是发出
    NumberFormattingException
    ,因为输入值太大
作业试图让你建立自己的机制来添加两个数字。以下是您应该采取的步骤:

  • 取两个输入字符串,例如
    “134”
    “258”
    。由于大小限制,不应将其转换为长字符
  • 将最右边的两个整数相加,在本例中为
    4
    8
    。如果该数字小于10,则可以前进到下一个整数。否则,如果数字等于或大于10(在我们的例子中,它是
    12
    ),则从右侧开始前进到下两个整数(
    3
    5
    )将1添加到这些整数。在我们的例子中,
    3+5+1=9
    。如果该数字等于或大于10,则在下一个整数上加1。就我们而言,情况并非如此。重复这些步骤,直到您拥有该数字的所有数字
  • 因此,在代码中,您有:

    public String add(String a, String b) {
        // I assume the strings are equal of length. If they are not, they
        // should be padded with zeroes. Otherwise, you can check if one string
        // has been 'exhaused', avoiding an IndexOutOfBoundsException.
    
        // The carry is the number which is 'dragged' to the next two integers
        // when it is greater than 9. While adding no more than two numbers, the
        // carry will always be 0 or 1.
        int carry = 0;
        // Our result as a string.
        String result = "";
    
        // Start at the right-most part the string, because that is
        // the least significant number.
        for (int i = a.length() - 1; i >= 0; i--) {
            // A string is an array of characters, and the characters '0' till
            // '9' have the ASCII values of 48 till 57. So if we just subtract
            // 48 from the given character, we have the digit the character
            // represents.
            int digitA = a.charAt(i) - 48;
            int digitB = b.charAt(i) - 48;
    
            // Add both digits and the carry.
            int resultingNumber = digitA + digitB + carry;
            if (resultingNumber >= 10) {
                // We only need the last digit, so we're using the modulo
                // operator, which calculats the remainder. Then we prepend our
                // number to our result string, creating a new result string.
                // You should rather use the StringBuilder class, but for
                // readability, I didn't.
                result = (resultingNumber % 10) + result;
                carry = 1;
            }
            else {
                result = resultingNumber + result;
                carry = 0;
            }
        }
        // Add the last carry to our result string, if available.
        if (carry > 0) {
            result = carry + result;
        }
        return result;
    }
    
    我添加了很多注释来解释代码


    请注意,我还避免使用StringBuilder和三元if语句来提高可读性。

    是否允许使用
    BigDecimal
    s?如何打印输出?不允许使用BigInteger或BigDecimal。是否查看了
    long
    值的范围?这与您试图添加到一起的值相比如何?听起来你的作业基本上是“自己实现解析和加法”。@JonSkeet是的,先生,这是我无法通过的测试用例之一。我甚至不知道如何添加这些数字。我不能使用其他类。我不能拆分它们。你让添加数字看起来像个孩子。非常感谢。