Leetcode-415. 字符串相加

61 阅读1分钟

思路

模拟普通加法, 将短的字符串填充0,将长的字符串填充一个0(以防进位使用(如"1" + "9")),之后使用逐位加法即可。

代码

lass Solution {
    public String addStrings(String num1, String num2) {
        if(num1.length() < num2.length()){
            String temp = num1;
            num1 = num2;
            num2 = temp;
        }
        StringBuffer num1Buf = new StringBuffer(num1);
        StringBuffer num2Buf = new StringBuffer(num2);
        num1Buf.insert(0, "0");
        for(int i = 0; i < num1.length() - num2.length() + 1; i++){
            num2Buf.insert(0,"0");
        }
        int flag = 0;
        StringBuffer res = new StringBuffer();
        for(int i = num1Buf.length() - 1; i >= 0; i--){
            int tempVal = num1Buf.charAt(i) - 48 + num2Buf.charAt(i) - 48  + flag;
            System.out.println(tempVal);
            flag = tempVal / 10;
            res.insert(0,(tempVal % 10)+"");
        }
        if(res.charAt(0) != '0')
            return res.toString();
        return res.toString().substring(1, res.length());
    }
}