🌗 415. 字符串相加

吞佛童子2022年10月10日
  • algorithm
  • String
  • 双指针
小于 1 分钟

🌗 415. 字符串相加

难度: 🌗

问题描述

img_5.png


解法

class Solution {
    public String addStrings(String num1, String num2) {
        // 思路:
        // 遍历 
        int m = num1.length();
        int n = num2.length();
        StringBuilder sb = new StringBuilder();
        int i = m - 1;
        int j = n - 1;
        int c = 0;
        while(i >= 0 && j >= 0) {
            int a = num1.charAt(i) - '0';
            int b = num2.charAt(j) - '0';
            int cur = a + b + c;
            if(cur >= 10) {
                c = 1;
                cur -= 10;
            } else {
                c = 0;
            }
            sb.insert(0, cur);
            i --;
            j --;
        }
        while(i >= 0) {
            int a = num1.charAt(i) - '0';
            int cur = a + c;
            if(cur >= 10) {
                c = 1;
                cur -= 10;
            } else {
                c = 0;
            }
            sb.insert(0, cur);
            i --;
        }
        while(j >= 0) {
            int b = num2.charAt(j) - '0';
            int cur = b + c;
            if(cur >= 10) {
                c = 1;
                cur -= 10;
            } else {
                c = 0;
            }
            sb.insert(0, cur);
            j --;
        }
        if(c == 1) {
            sb.insert(0, 1);
        }
        return sb.toString();
    }
}

输出

img_4.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou