力扣-415-字符串相加

思路是模拟从低位到高位的按位相加,需要考虑进位

    public String addStrings(String num1, String num2) {
        int bitLen1 = num1.length() - 1, bitLen2 = num2.length() - 1;
        StringBuilder stringBuilder = new StringBuilder();
        int carry = 0;
        while (bitLen1 >= 0 || bitLen2 >= 0 && carry > 0) {
            int bit1 = bitLen1 >= 0 ? num1.charAt(bitLen1) - '0' : 0;
            int bit2 = bitLen2 >= 0 ? num2.charAt(bitLen2) - '0' : 0;
            int sum = bit1 + bit2 + carry;
            carry = sum / 10;
            stringBuilder.append(sum % 10);
            bitLen1--;
            bitLen2--;
        }
        stringBuilder.reverse();
        return stringBuilder.toString();
    }
posted @ 2024-07-27 20:23  YaosGHC  阅读(2)  评论(0编辑  收藏  举报