写一个大数相加的算法java
时间: 2024-09-30 09:02:30 浏览: 38
在Java中编写大数相加的算法,我们通常会使用字符串处理来避免溢出问题,因为整型数据在相加过程中可能会超出其最大范围。这里提供一个基于字符串的简单算法:
```java
public class BigIntegerAddition {
public static String addStrings(String num1, String num2) {
int len1 = num1.length(), len2 = num2.length();
StringBuilder result = new StringBuilder(len1 + len2);
int i = len1 - 1, j = len2 - 1;
int carry = 0;
while (i >= 0 || j >= 0) {
int n1 = i >= 0 ? num1.charAt(i--) - '0' : 0; // get digit from first number
int n2 = j >= 0 ? num2.charAt(j--) - '0' : 0; // get digit from second number
int sum = n1 + n2 + carry; // calculate sum
result.append(sum % 10); // append the sum to the result string
carry = sum / 10; // update carry for next iteration
}
// If there's a carry left after adding all digits, add it as leading zero
if (carry > 0) {
result.insert(0, carry);
}
return result.toString(); // return the final result
}
}
// 使用示例
public static void main(String[] args) {
String num1 = "1234567890";
String num2 = "9876543210";
System.out.println(addStrings(num1, num2)); // 输出:11111111100
}
```
阅读全文