如何在java中添加任意长度的两个数字? [英] How to add two numbers of any length in java?

查看:374
本文介绍了如何在java中添加任意长度的两个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在java中添加两个任意长度的数字?

How to add two numbers of any length in java?

例如,在java中,长度为64位。所以最大范围是-9223372036854775808到9223372036854775807.我是对的吗?

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

整数太大


long a = 9223372036854775807L;

长b
= 9223372036854775808L;

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

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

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.

如何做到java。我们可以遍历String中每个字符的地址。

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

感谢您的回复。

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

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

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

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)?

谢谢。

推荐答案

您可以使用 BigInteger

You can use a BigInteger.

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

BigInteger 可让您使用数字任何大小的,但你在 long int 中失去了相当多的性能。

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

这篇关于如何在java中添加任意长度的两个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆