Java实现BigInteger⼤数相加
时常见到这个题,由于long型的变量有上限,不能进⾏⼤数操作,先转化为⼀个⼀个字符分别运算,加减乘除同理。
/**
* @author _yiyi
* @create 2018/8/23
*/
public class BigNumInteger {
public String number1 = "11524323423435";
public String number2 = "922323";
/***
*
* @param number1
* @param number2
* @return结果字符串
* 1,先出字符串⼤⼩,然后使其两个字符串长度⼀致,短在前⾯补齐0
* 2,按照加法运算原则从后⾯往前加,设置进位标识flag,进位加⼀。
* 3,重复2运算到结束。
*/
private String bigNumAdd(String number1, String number2) {
int maxLength, minLength;
int flag = 0;//进位标志
StringBuilder temp = new StringBuilder();
maxLength = number1.length() > number2.length() ? number1.length() : number2.length();
minLength = number1.length() < number2.length() ? number1.length() : number2.length();
String result = "";//结果集
//先把2个不同长度的字符串补齐0,短的那⼀边前⾯补齐0,例如,1234,0012.
for (int i = 0; i < maxLength - minLength; i++) {
temp.append("0");
}
if (minLength == number1.length()) {
number1 = temp + number1;
} else number2 = temp + number2;
for (int i = maxLength-1; i >=0; i--) {
int tempA =Integer.parseInt(String.valueOf(number1.charAt(i)));
int tempB = Integer.parseInt(String.valueOf(number2.charAt(i)));
int tempI = 0;
if (tempA + tempB >= 10) {
tempI = tempA + tempB - 10 + flag;
flag = 0;
flag++;
} else {
tempI = tempA + tempB + flag;
flag = 0;
}
result = tempI + result;
}
if (flag == 1)
result = flag + result;
return result;
}
public static void main(String[] args) {
BigNumInteger bigNumInteger = new BigNumInteger();
System.out.println(bigNumInteger.bigNumAdd(bigNumInteger.number1, bigNumInteger.number2));
}
java valueof}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。