一、工具类
import java.util.ArrayList;
import java.util.List;
public class CalculateUtil {
/**
* 计算两个正整数的和,n1+n2
*/
public static String sum(String n1, String n2) {
//若n1和n2位数不一样,则将少的数补0
int puchZero = Math.abs(n1.length() - n2.length());
String newStr = "";
for (int i = 0; i < puchZero; i++) {
newStr += 0;
}
if (n1.length() > n2.length()) {
n2 = newStr + n2;
} else {
n1 = newStr + n1;
}
//从个位开始将n1和n2相加,结果放入list中
char[] ch1 = n1.toCharArray();
char[] ch2 = n2.toCharArray();
//下一位进位要加的数
int nextAdd = 0;
List<Integer> list = new ArrayList<>();
for (int i = ch1.length - 1; i >= 0; i--) {
int num1 = ch1[i] - '0';
int num2 = ch2[i] - '0';
int sum = num1 + num2 + nextAdd;
if (sum > 9) {
if (i != 0) {
nextAdd = 1;
list.add(sum % 10);
} else {
list.add(sum);
}
} else {
nextAdd = 0;
list.add(sum);
}
}
//翻转list,输出结果
String result = "";
for (int i = list.size() - 1; i >= 0; i--) {
result += list.get(i);
}
return result;
}
/**
* 计算两个正整数的差,n1-n2
*/
public static String sub(String n1, String n2) {
String symbol = "";
if (n1.equals(n2)) {
return "0";
}
//n1Moren2标记n1是否大于n2
boolean n1Moren2 = n1.length() > n2.length();
if (n1.length() == n2.length() && !n1.equals(n2)) {
for (int i = 0; i < n2.length(); i++) {
int temN1 = n1.charAt(i) - '0';
int temN2 = n2.charAt(i) - '0';
if (temN1 != temN2) {
n1Moren2 = temN1 > temN2;
break;
}
}
}
//n1小于n2则交换n1和n2,使n1大于n2
if (!n1Moren2) {
symbol = "-";
String temp = n1;
n1 = n2;
n2 = temp;
}
//交换后如果长度不等,则对n2前面补0,使n1和n2的长度相等
if (n1.length() != n2.length()) {
int puchZero = n1.length() - n2.length();
String newStr = "";
for (int i = 0; i < puchZero; i++) {
newStr += 0;
}
n2 = newStr + n2;
}
char[] ch1 = n1.toCharArray();
char[] ch2 = n2.toCharArray();
String result = "";
boolean nextExcuse = false;
List<Integer> list = new ArrayList<>();
for (int i = ch1.length - 1; i >= 0; i--) {
int num1 = ch1[i] - '0';
int num2 = ch2[i] - '0';
if (!nextExcuse) {//该位没被借位过
if (num1 >= num2) {
list.add(num1 - num2);
} else {
nextExcuse = true;
list.add(10 + num1 - num2);
}
} else {//该位被借位过
if (num1 > num2) {
list.add(num1 - 1 - num2);
nextExcuse = false;
} else {
list.add(9 + num1 - num2);
}
}
}
//去除最开始的连续0,输出结果
int zeroPostion = -1;
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i) != 0) {
break;
}
if (i >= 1 && list.get(i - 1) != 0) {
zeroPostion = i;
break;
}
}
int startPostion = zeroPostion == -1 ? list.size() - 1 : zeroPostion - 1;
for (int i = startPostion; i >= 0; i--) {
result += list.get(i);
}
return symbol + result;
}
}
二、测试
public class MainServer {
public static void main(String[] args) {
String n1 = "1009901999998809979999999999";
String n2 = "989096189599989309877571236897";
System.out.println("和:"+CalculateUtil.sum(n1, n2));
System.out.println("差:"+CalculateUtil.sub(n1, n2));
}
}
输出:
和:990106091599988119857571236896
差:-988086287599990499897571236898
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/80248.html