java中如何将两个任意长度的数字相加?

发布于 2024-09-24 17:52:49 字数 577 浏览 4 评论 0原文

java中如何将两个任意长度的数字相加?

例如,在java中,long大小是64位。所以最大范围是 -9223372036854775808 到 9223372036854775807。我对吗?

因此,如果我们想添加一个大于此值的数字,如下所示,我会收到错误

“整数太大”

长a = 9223372036854775807L;
长b = 9223372036854775808L;

在C中,我们可以将这些数字作为字符数组,通过遍历每个字符的地址并使用某种数据结构,我们可以将两个任意大小的数字相加。

如何做到这一点java.我们可以遍历String中每个字符的地址吗?


感谢您的回复。

我尝试通过将数字作为字符串传递并从末尾添加每个字符来进行编码。它对我来说效果很好。

使用 BigInteger 和我上面指定的方法将两个非常大的数字相加(从末尾添加每个字符并将余数存储在临时变量中并继续)之间有什么大的区别吗? BigInteger的底层机制与我的代码相同(从末尾添加每个字符)吗?

谢谢。

How to add two numbers of any length in java?

Say for example, in java long size is 64 bit. So the maximum range is -9223372036854775808 to 9223372036854775807. Am i right?

So if we want to add a number which is greater than this like below, i got a error

" Integer Number too large"

long a = 9223372036854775807L;
long b
= 9223372036854775808L;

In C, we can take those numbers as char array, by traversing through the address of each char and use some data structure, we can add two numbers of any size.

How to do it java. Can we traverse through the address of each character in String.


Thanks for your responses.

I have tried to code by passing the numbers as string and add each character from the end. It works fine for me.

Is there any big difference between the addition of two very large numbers using BigInteger and the method, i specified above (add each character from end and store remainder in temporary variable and goes on).
Is the underlying mechanism of BigInteger is same as my code(add each character from end)?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

浅忆 2024-10-01 17:52:49

您可以使用 BigInteger< /a>.

BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("9223372036854775808");
BigInteger result = a.add(b);

BigInteger 可以让您处理任意大小的数字,但与 longint 相比,您会损失相当多的性能。

You can use a BigInteger.

BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("9223372036854775808");
BigInteger result = a.add(b);

The BigInteger will let you work with numbers of any size, but you lose a considerable amount of performance over long or int.

一个人练习一个人 2024-10-01 17:52:49

BigInteger 可以让您处理任意大小的数字,但与 longint 相比,您会损失相当多的性能。< /p>

实际上,如果您只需要运行此操作一次(用户输入两个数字,然后返回结果),那么使用 BigInteger 就可以了。但如果您需要多次执行加法运算,您实际上可以使用您自己的大整数实现。当我参加 ACM 比赛时,我们经常使用我们自己的基于 char 数组的实现(在 C++ 中)。我建议使用以下代码。假设有两个整数数组A和B。A[0]B[0]存储对应编号的镜头。 A[i]B[i] 存储数字本身。 A[1]B[1] 是最低有效数字。因此数字 1234 将对应于这样一个数组:{4,4,3,2,1}。

现在,假设我们想要对这些数字求和并以相同的格式将它们存储在数组 C 中。以下是您可以使用的代码示例:

int len1 = A[0],  len2 = B[0], divisor = 0;
int len = len1 >= len2 ? len1 : len2;
for (int i=1;i<=len;i++) {
  if (i>len1) C[i] = B[i]+divisor;
  else if (i>len2) C[i] = A[i]+divisor;
  else C[i] = A[i]+B[i]+divisor;
  divisor = C[i]/10;
  C[i] %= 10;
}
while (divisor>0) {
  C[++len] = divisor%10;
  divisor /= 10;
}
C[0] = len;

该代码使用简单的算术加法规则,并且应该比 BigInteger 一般实现快得多。享受使用它的乐趣。

The BigInteger will let you work with numbers of any size, but you lose a considerable amount of performance over long or int.

Actually, if you just need to run this operation once (user enters two numbers, and gets the result back), using BigInteger is fine. But if you need to perform the addition operation many times, you could use really your own implementation of big integer. When I was competing in ACM matches, we often used our own implementations based on char arrays (in C++). I suggest the following code. It is assumed that there are two arrays of integers, A and B. A[0] and B[0] store the lens of the corresponding numbers. A[i] and B[i] stores the digits themselves. A[1] and B[1] are the least significant digits. Therefore the number 1234 would correspond to such an array: {4,4,3,2,1}.

Now, suppose we want to sum these numbers and store them in array C in the same format. Here is an example of code, that you could use:

int len1 = A[0],  len2 = B[0], divisor = 0;
int len = len1 >= len2 ? len1 : len2;
for (int i=1;i<=len;i++) {
  if (i>len1) C[i] = B[i]+divisor;
  else if (i>len2) C[i] = A[i]+divisor;
  else C[i] = A[i]+B[i]+divisor;
  divisor = C[i]/10;
  C[i] %= 10;
}
while (divisor>0) {
  C[++len] = divisor%10;
  divisor /= 10;
}
C[0] = len;

That code uses the simple rules of arithmetic addition and should work significantly faster than the BigInteger general implementation. Have fun with using that.

中二柚 2024-10-01 17:52:49

使用 BigInteger
这里是一个示例。

示例代码(基于上面的链接)-

BigInteger reallyBig1 = new BigInteger("1234567890123456890");
BigInteger reallyBig2 = new BigInteger("2743534343434361234");
reallyBig = reallyBig.add(reallyBig2);

Use BigInteger.
Here is an example.

Example code (based on above link) -

BigInteger reallyBig1 = new BigInteger("1234567890123456890");
BigInteger reallyBig2 = new BigInteger("2743534343434361234");
reallyBig = reallyBig.add(reallyBig2);
情场扛把子 2024-10-01 17:52:49

查看 BigInteger 类。它将能够对非常大的数字执行您正在寻找的操作。

http://download.oracle.com/ javase/1.4.2/docs/api/java/math/BigInteger.html

Check out the BigInteger class. It will be able to perform the operations you are looking for on really large numbers.

http://download.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html

年少掌心 2024-10-01 17:52:49

使用 BigInteger 和我上面指定的方法相加两个非常大的数字之间有什么大的区别吗(从末尾添加每个字符并将余数存储在临时变量中并继续)。

例如,不同之处在于您可以使用更大的基数。假设基数是 10000,而不仅仅是 10。当我之前的答案的代码修改如下时:

int len1 = A[0],  len2 = B[0], divisor = 0;
int len = len1 >= len2 ? len1 : len2;

for (int i=1;i<=len;i++) {
  if (i>len1) C[i] = B[i]+divisor;
  else if (i>len2) C[i] = A[i]+divisor;
  else C[i] = A[i]+B[i]+divisor;
  divisor = C[i]/10000;
  C[i] %= 10000;
}
while (divisor>0) {
  C[++len] = divisor%10000;
  divisor /= 10000;
}
C[0] = len;

在这种情况下,代码运行速度快 4 倍(因为虚拟机在算术运算中没有区别,因为它们依赖于仅常数)。此外,这意味着整数数组将缩小 4 倍。这导致的唯一问题是如何格式化输出。

Is there any big difference between the addition of two very large numbers using BigInteger and the method, i specified above (add each character from end and store remainder in temporary variable and goes on).

The difference is that you could use a larger radix, for example. Suppose the radix is 10000, not just 10. When the code of my previous answer would be modified like this:

int len1 = A[0],  len2 = B[0], divisor = 0;
int len = len1 >= len2 ? len1 : len2;

for (int i=1;i<=len;i++) {
  if (i>len1) C[i] = B[i]+divisor;
  else if (i>len2) C[i] = A[i]+divisor;
  else C[i] = A[i]+B[i]+divisor;
  divisor = C[i]/10000;
  C[i] %= 10000;
}
while (divisor>0) {
  C[++len] = divisor%10000;
  divisor /= 10000;
}
C[0] = len;

In that case the code runs 4 time faster (since there is no difference for the virtual machine in arithmetic operations, since they depend on the constant only). Also, this means, that the array of integers will be 4 times smaller. The only problem this causes is how to format the output.

轻许诺言 2024-10-01 17:52:49

创建一个堆栈类并从用户处获取数字作为字符串,并将它们转换为字符串并将它们推入堆栈。
在这里,我编写了两个大数相加的完整代码。还包括堆栈类。
只需输入 cmd javac mystack.java 然后输入 java mystack

import java.util.*;
public class mystack {
int maxsize=0;
int top=-1;
int array []=new int [0];


public mystack (int size)
{
    maxsize=size;
    array=new int [maxsize];
}

public void push (int x)
{   
    top=top+1;
    array[top]=x;
}

public int pop ()
{
    int elt=array[top];
    top--;
    return elt;

}

public boolean stackisfull()
{
    return(top==maxsize-1);
}

public boolean stackisempty()
{
    return(top==-1);
}

public int peak ()
{
    int peak =array[top];
    return peak;
}

public static void main (String args[]){
Scanner in=new Scanner (System.in);

System.out.println("Enter the 1st number");
String number1 = in.nextLine();
System.out.println();
System.out.println("Enter the 2nd number");
String number2 = in.nextLine();
System.out.println();

String temp="";




 if(number1.length()>number2.length())
 {
    temp=number1;
    number1=number2;
    number2=temp;
 }

    int k=0;


 mystack S1 = new mystack (number1.length());

      for(int i=0;i<number1.length();i++)
       {
            String str=Character.toString(number1.charAt(i));
            S1.push(Integer.parseInt(str));
       } 

 mystack S2 = new mystack (number2.length());

     for(int i=0;i<number2.length();i++)
        {
            String str=Character.toString(number2.charAt(i));
            S2.push(Integer.parseInt(str));
        } 

 mystack S3 =new mystack (number2.length());

 while(!S1.stackisempty())
 {
     int x=S1.pop();
     int y=S2.pop();

     int times=(x+y+k)/10; int remainder =(x+y+k)%10;
     k=0;

     if(times==0)
     {
        S3.push(remainder);
     }

     else
     {
         S3.push(remainder);
         k=1;
     }
 }
    while(!S2.stackisempty())
    {
        if(k==1)
        {
            S3.push(k+S2.pop());
            k=0; 
        }
       else
        S3.push(S2.pop());
    }

    System.out.print("Addition is ");

    while(!S3.stackisempty())
    {
        System.out.print(S3.pop());
    }

}
}

Create a stack class and get numbers as string from user and convert them into string and push them into stacks.
Here I've written the full code for the addition of two large numbers. stack class also included.
Just type in cmd javac mystack.java then java mystack

import java.util.*;
public class mystack {
int maxsize=0;
int top=-1;
int array []=new int [0];


public mystack (int size)
{
    maxsize=size;
    array=new int [maxsize];
}

public void push (int x)
{   
    top=top+1;
    array[top]=x;
}

public int pop ()
{
    int elt=array[top];
    top--;
    return elt;

}

public boolean stackisfull()
{
    return(top==maxsize-1);
}

public boolean stackisempty()
{
    return(top==-1);
}

public int peak ()
{
    int peak =array[top];
    return peak;
}

public static void main (String args[]){
Scanner in=new Scanner (System.in);

System.out.println("Enter the 1st number");
String number1 = in.nextLine();
System.out.println();
System.out.println("Enter the 2nd number");
String number2 = in.nextLine();
System.out.println();

String temp="";




 if(number1.length()>number2.length())
 {
    temp=number1;
    number1=number2;
    number2=temp;
 }

    int k=0;


 mystack S1 = new mystack (number1.length());

      for(int i=0;i<number1.length();i++)
       {
            String str=Character.toString(number1.charAt(i));
            S1.push(Integer.parseInt(str));
       } 

 mystack S2 = new mystack (number2.length());

     for(int i=0;i<number2.length();i++)
        {
            String str=Character.toString(number2.charAt(i));
            S2.push(Integer.parseInt(str));
        } 

 mystack S3 =new mystack (number2.length());

 while(!S1.stackisempty())
 {
     int x=S1.pop();
     int y=S2.pop();

     int times=(x+y+k)/10; int remainder =(x+y+k)%10;
     k=0;

     if(times==0)
     {
        S3.push(remainder);
     }

     else
     {
         S3.push(remainder);
         k=1;
     }
 }
    while(!S2.stackisempty())
    {
        if(k==1)
        {
            S3.push(k+S2.pop());
            k=0; 
        }
       else
        S3.push(S2.pop());
    }

    System.out.print("Addition is ");

    while(!S3.stackisempty())
    {
        System.out.print(S3.pop());
    }

}
}
月隐月明月朦胧 2024-10-01 17:52:49
public class AddNumbers {
    public static void main(String args[]) {
        String a = new String("3999988889999999995555558888999444333333333222229998877666555444888888");
        String b = new String("56867865876989679765465456412332199");
        int loop1 = 0;
        int loop2 = 0;
        StringBuilder sum = new StringBuilder("");
        int carry = 0;
        for (loop1 = a.length() - 1, loop2 = b.length() - 1; loop1 >= 0 || loop2 >= 0; loop1--, loop2--) {
            int indiv1 = 0;
            if (loop1 >= 0)
                indiv1 = Integer.parseInt("" + a.charAt(loop1));
            int indiv2 = 0;
            if (loop2 >= 0)
                indiv2 = Integer.parseInt("" + b.charAt(loop2));
            int summation = indiv1 + indiv2 + carry;
            double d = Math.floor(summation / 10);
            carry = (int) d;
            int sum2 = summation % 10;
            sum.append(sum2);
        }
        System.out.println(sum.reverse());
    }
}
public class AddNumbers {
    public static void main(String args[]) {
        String a = new String("3999988889999999995555558888999444333333333222229998877666555444888888");
        String b = new String("56867865876989679765465456412332199");
        int loop1 = 0;
        int loop2 = 0;
        StringBuilder sum = new StringBuilder("");
        int carry = 0;
        for (loop1 = a.length() - 1, loop2 = b.length() - 1; loop1 >= 0 || loop2 >= 0; loop1--, loop2--) {
            int indiv1 = 0;
            if (loop1 >= 0)
                indiv1 = Integer.parseInt("" + a.charAt(loop1));
            int indiv2 = 0;
            if (loop2 >= 0)
                indiv2 = Integer.parseInt("" + b.charAt(loop2));
            int summation = indiv1 + indiv2 + carry;
            double d = Math.floor(summation / 10);
            carry = (int) d;
            int sum2 = summation % 10;
            sum.append(sum2);
        }
        System.out.println(sum.reverse());
    }
}
风月客 2024-10-01 17:52:49
    import java.math.BigInteger;
    import java.util.Scanner;

    public class BigIntergerSumExample {

        public static void main(String args[]) {

            BigInteger number1;
            BigInteger number2;
            BigInteger sum;
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter the value of number 1");
            number1 = sc.nextBigInteger();
            System.out.println("Enter the value of number 2");
            number2 = sc.nextBigInteger();


            BigInteger a = new BigInteger(""+number1);
            BigInteger b = new BigInteger(""+number2);
            BigInteger result = a.add(b);

            System.out.println("Sum is Two numbers : -> " + result);
        }

    }

**OUTPUT IS** 

Enter the value of number 1
1111111111111111111111111111111111111111111111111
Enter the value of number 2
2222222222222222222222222222222222222222222222222
Sum is Two numbers : -> 
3333333333333333333333333333333333333333333333333

导入 java.math.BigInteger 可以让您处理任何大小的数字,

    import java.math.BigInteger;
    import java.util.Scanner;

    public class BigIntergerSumExample {

        public static void main(String args[]) {

            BigInteger number1;
            BigInteger number2;
            BigInteger sum;
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter the value of number 1");
            number1 = sc.nextBigInteger();
            System.out.println("Enter the value of number 2");
            number2 = sc.nextBigInteger();


            BigInteger a = new BigInteger(""+number1);
            BigInteger b = new BigInteger(""+number2);
            BigInteger result = a.add(b);

            System.out.println("Sum is Two numbers : -> " + result);
        }

    }

**OUTPUT IS** 

Enter the value of number 1
1111111111111111111111111111111111111111111111111
Enter the value of number 2
2222222222222222222222222222222222222222222222222
Sum is Two numbers : -> 
3333333333333333333333333333333333333333333333333

import java.math.BigInteger will let you work with numbers of any size,

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文