package com.michael.j2se;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class BigIntegerAdd {
public static void main(String[] args) throws Exception {
System.out.println("请输入第一个大数字");
String s1 = input();
System.out.println("请输入第二个大数字");
String s2 = input();
add(s1, s2);
}
private static void add(String s1, String s2) {
Stack<Integer> st1 = new Stack<Integer>();
Stack<Integer> st2 = new Stack<Integer>();
Stack<Integer> result = new Stack<Integer>();
int templen = 0;
String strvalue = "";
// 调整长度相同
if (s1.length() >= s2.length()) {
templen = s1.length() - s2.length();
s2 = maxlen(s2, templen); // 208,2
} else {
templen = s2.length() - s1.length();
s1 = maxlen(s1, templen);
}
try {
for (int i = 0; i < s1.length(); i++) {
st1.push(Integer.parseInt(String.valueOf(s1.charAt(i))));
st2.push(Integer.parseInt(String.valueOf(s2.charAt(i))));
// st1.push(s1.charAt(i) - '0');
// st2.push(s2.charAt(i) - '0');
int m = st1.pop() + st2.pop();
result.push(m);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
int temp = 0;
while (!result.empty()) {
int t = result.pop();
if (t >= 10) {
strvalue = String.valueOf(t + temp - 10) + strvalue;
temp = t / 10;
} else {
strvalue = String.valueOf(t + temp) + strvalue;
temp = 0;
}
}
// 考虑最后一位进位
if (temp != 0) {
StringBuffer sb = new StringBuffer();
sb.append(strvalue);
strvalue = sb.insert(0, temp).toString();
}
display(strvalue);
}
/**
* 接受输入
*
* @return
*/
private static String input() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = "";
//这里可以用正则表达式验证输入的是否都为数字
try {
s = br.readLine();
} catch (Exception e) {
e.getMessage();
}
return s;
}
/**
* 输出结果
*
* @param result
*/
private static void display(String str) {
System.out.print(str);
}
/**
* 添0实现字符串长度一样
* @param str
* @param templen
* @return
*/
private static String maxlen(String str, int templen) {
String strmax = null;
StringBuffer buff = new StringBuffer();
for (int i = 0; i < templen; i++) {
buff.append("0");
}
strmax = buff.toString() + str;
return strmax;
}
}
用堆栈实现长整数相加
最新推荐文章于 2022-05-12 09:53:06 发布