Leetcode 415. Add Strings (Easy) (cpp)

来源:互联网 发布:云计算java工程师招聘 编辑:程序博客网 时间:2024/05/16 19:00

Leetcode 415. Add Strings (Easy) (cpp)

Tag: Math

Difficulty: Easy


/*415. Add Strings (Easy)Given two non-negative numbers 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.*/class Solution {public:    string addStrings(string num1, string num2) {        string res;        int i = num1.length() - 1, j = num2.length() - 1;        long carry = 0;        while ( i >= 0 || j >= 0 || carry > 0) {            if (i >= 0) {                carry = (num1[i--] - '0') + carry;            }            if (j >= 0) {                carry = (num2[j--] - '0') + carry;            }            res += to_string(carry % 10);            carry /= 10;        }        reverse(res.begin(), res.end());        return res;    }};


0 0
原创粉丝点击