java计算两个数相加,解决溢出问题

  • 输入:
  • 包含两个非负数 a 和 b,以空格分隔;a 和 b 保证小于 2^32.

 

  • 输出:
  • 你的输出是对一行数据处理的结果,也即 a+b 的结果。

 

  • 输入样例:233 666
  • 输出样例:899
import java.util.Stack;

public class mitest {
    public static String myTest(String line) {
        int j = -1;
        Stack firstNumStack = new Stack();
        Stack secondNumStack = new Stack();
        Stack sum = new Stack();
        for (int i = 0; i < line.length(); i++) {
            if (!Character.isDigit(line.charAt(i))) {
                j = j + 1;
                continue;
            } else if (j == -1) {
                firstNumStack.push(Integer.parseUnsignedInt(String.valueOf(line.charAt(i))));
            } else if (j > -1) {
                secondNumStack.push(Integer.parseUnsignedInt(String.valueOf(line.charAt(i))));
            }
        }
        int maxLen = 0;
        if (firstNumStack.size() >= secondNumStack.size()) {
            maxLen = firstNumStack.size();
        }
        else {
            maxLen = secondNumStack.size();
        }

        int carry = 0;
        int firstNum;
        int secondNum;
        int tmpSum;
        while (maxLen != 0) {
            try {
                 firstNum = firstNumStack.pop();
            } catch (Exception e1) {
                firstNum = 0;
            }
            try {
                secondNum = secondNumStack.pop();
            } catch (Exception e2) {
                secondNum = 0;
            }
            tmpSum = firstNum + secondNum + carry;
            carry = tmpSum / 10;
            sum.push(tmpSum - carry * 10);
            maxLen -- ;
        }
        if (carry != 0) {
            sum.push(carry);
        }
        StringBuffer stringBuffer = new StringBuffer();
        while (sum.size() != 0) {
            stringBuffer.append(String.valueOf(sum.pop()));
        }
        return stringBuffer.toString();
    }
    public static void main(String[] args)
    {
        System.out.println(myTest ("100 456909"));
    }
}

你可能感兴趣的:(java计算两个数相加,解决溢出问题)