Java简单实现大数相加
public class BigNumberAdd {
public static String add(String num1, String num2) {
int m = num1.length();
int n = num2.length();
StringBuilder sb = new StringBuilder();
int carry = 0;
int index1 = m - 1;
int index2 = n - 1;
while (carry != 0 || index1 >= 0 || index2 >= 0) {
int a = 0;
int b = 0;
if (index1 >= 0) {
a = num1.charAt(index1) - '0';
index1--;
}
if (index2 >= 0) {
b = num2.charAt(index2) - '0';
index2--;
}
int tmp = (a + b + carry) % 10;
carry = (a + b + carry) / 10;
sb.append(tmp);
}
sb.reverse();
return sb.toString();
}
public static int compareAbsoluteValue(String num1, String num2) {
String s1 = num1.charAt(0) == '-' ? num1.substring(1) : num1;
String s2 = num2.charAt(0) == '-' ? num1.substring(1) : num2;
if (s1.length() > s2.length()) {
return 1;
}
else if (s1.length() < s2.length()) {
return -1;
}
else {
int n = s1.length();
int index = 0;
while (index < n) {
if (s1.charAt(index) > s2.charAt(index)) {
return 1;
}
else if (s1.charAt(index) < s2.charAt(index)) {
return -1;
}
index++;
}
}
return 0;
}
public static boolean isSameNumber(String s1, String s2) {
return isPositive(s1) == isPositive(s2);
}
public static String minus(String num1, String num2) {
int m = num1.length();
int n = num2.length();
int carry = 0;
int index1 = m - 1;
int index2 = n - 1;
StringBuilder sb = new StringBuilder();
while (carry != 0 || index1 >= 0 || index2 >= 0) {
int a = 0;
int b = 0;
if (index1 >= 0) {
a = num1.charAt(index1) - '0';
index1--;
}
if (index2 >= 0) {
b = num2.charAt(index2) - '0';
index2--;
}
int tmp = (a - b - carry);
if (tmp < 0) {
tmp += 10;
carry = 1;
}
else {
carry = 0;
}
sb.append(tmp);
}
sb.reverse();
while (sb.length() > 0 && sb.charAt(0) == '0') {
sb.deleteCharAt(0);
}
return sb.toString();
}
private static boolean isPositive(String num1) {
return !(num1.charAt(0) == '-');
}
public static String addTwoBigNumber(String num1, String num2) {
boolean isSame = isSameNumber(num1, num2);
if (isSame) {
boolean isPositive = isPositive(num1);
if (isPositive) {
return add(num1, num2);
}
else {
return "-" + (add(num1.substring(1), num2.substring(1)));
}
}
else {
int compareResult = compareAbsoluteValue(num1, num2);
if (compareResult == 0) {
return "";
}
boolean isPositive = isPositive(num1);
if (compareResult == -1) {
if (isPositive) {
return "-" + minus(num2.substring(1), num1);
}
else {
return minus(num2, num1.substring(1));
}
}
else {
if (isPositive) {
return minus(num1, num2.substring(1));
}
else {
return "-" + minus(num1.substring(1), num2);
}
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)