兩個純數字字符串相加Java實現版

 

/**
 * 兩個純數字字符串相加,不能用大整數相加的方法,無論多長的數字均可以相加
 * 考慮進位
 */
public class TwoStringAdd {
    public static void solution(String num1, String num2) {
        StringBuffer sb = new StringBuffer();
        int len1 = num1.length();
        int len2 = num2.length();
        int carry = 0;
        for (int i = len1-1, j = len2-1; i >=0 || j >=0 || carry ==1 ; i--, j--) {
            int a = i < 0 ? 0 : num1.charAt(i) - '0';
            int b = j < 0 ? 0 : num2.charAt(j) - '0';
            int h = (a + b + carry) % 10;
            carry = (a + b + carry) / 10;
            sb.append(h);
        }
        System.out.println(sb.reverse().toString());
    }
    public static void main(String[] args) {
        solution("123", "877");
    }
}

  輸出

1000

 

借鑑自B站視頻

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章