LeetCode 415 字符串相加

  • 思路

      大数相加,注意对进位的处理。

  • 代码
class Solution {
public:
    string addStrings(string num1, string num2) {
        //保证num1字符串为长度较长的字符串
        if(num1.length() < num2.length())swap(num1, num2);
        
        int len1 = num1.length();
        int len2 = num2.length();

        int i = len1 - 1;
        int j = len2 - 1;
        int jin = 0, temp = 0;

        while(i >= 0 && j >= 0){
            temp = num1[i] - 48 + num2[j--] - 48 + jin;
            jin = temp / 10;
            num1[i--] = (char)(temp%10 + 48);
        }

        while(i >= 0){
            temp = num1[i] - 48 + jin;
            jin = temp / 10;
            num1[i--] = (char)(temp%10 + 48);
        }

        if(jin != 0){
            num1 = to_string(jin) + num1;            
        }
        return num1;
    }
};

 

你可能感兴趣的:(#,LeetCode每日一题,常见面试题)