字符串相加Add Strings(給定兩個字符串形式的非負整數 num1 和num2 ,計算它們的和。)

/**
 * @author LemonLin
 * @Description :StringAddStrings
 * @date 19.6.13-22:47
 * Given two non-negative integers num1 and num2 represented as string, return the sum of num1
 * and num2.
 * Note:
 * The length of both num1 and num2 is < 5100.
 * Both num1 and num2 contains only digits 0-9.
 * Both num1 and num2 does not contain any leading zero.
 * You must not use any built-in BigInteger library or convert the inputs to integer directly.
 *給定兩個字符串形式的非負整數 num1 和num2 ,計算它們的和。
 * 注意:
 * num1 和num2 的長度都小於 5100.
 * num1 和num2 都只包含數字 0-9.
 * num1 和num2 都不包含任何前導零。
 * 你不能使用任何內建 BigInteger 庫, 也不能直接將輸入的字符串轉換爲整數形式。
 * 思路:題目要求不能直接用Integer的庫,那麼考慮用取出字符串中的每個字符-'0'來轉換爲整數差來計算,
 * 從後往前遍歷字符串,要考慮進位的問題。
 * 難點:獲得每個索引位置的數值之後怎麼拼接起來,比如從後往前獲得的數值是2,3,5,1.怎麼把這四個數字拼成
 *  1532
 *解答:這裏直接用stringbuilder的append方法,最後再reverse反轉一下,感覺不是很優雅,暫時沒想到其他
 *   辦法
 */
public class StringAddStrings {
    public String addStrings(String num1, String num2) {
        int index1=num1.length()-1,index2=num2.length()-1;
        int carry=0;
        StringBuilder stringBuilder = new StringBuilder();
        int temp1=0,temp2=0;
        int sum=0;
        while (index1>=0||index2>=0){
            //減字符'0'是爲了將字符轉換爲對應的整數
            if (index1 < 0){
                temp1 =0;
            }else {
                temp1 = num1.charAt(index1--)-'0';
            }
            if (index2 < 0){
                temp2 =0;
            }else {
                temp2 = num2.charAt(index2--)-'0';
            }
            sum=carry+temp1+temp2;
            stringBuilder.append(sum%10);
            carry = sum/10;
        }
        if (carry ==1){
            stringBuilder.append("1");
        }
        return stringBuilder.reverse().toString();
    }

    public static void main(String[] args) {
        String num1="122";
        String num2="23";
        System.out.println(new StringAddStrings().addStrings(num1, num2));
    }
}

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