Leetcode Add Strings 415

来源:互联网 发布:java 调用构造方法 编辑:程序博客网 时间:2024/06/05 02:36

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.
Subscribe to see which companies asked this question

题目链接

模拟吧
不过遇到一个bug
c++里面的string 不可以s[i]赋值 可以使用 s+=’a’

class Solution {public:    string addStrings(string num1, string num2) {        string ans="";        int l1=num1.length();        int l2=num2.length();        num1=reverse(num1);        num2=reverse(num2);        int len=0,carry=0;        if(l1<l2){            len=l2;        }        else{            len=l1;        }        for(int i=l1;i<len;i++)             num1+='0';        for(int i=l2;i<len;i++)            num2+='0';        for(int i=0;i<len;i++){            int a=num1[i]-'0';            int b=num2[i]-'0';            int temp=a+b+carry;            carry=temp/10;            temp=temp%10;            ans=ans+to_string(temp);        }        if(carry)ans=ans+to_string(carry);        return reverse(ans);    }    string reverse(string s){        int l=0,r=s.length()-1;        while(l<r){            s[l]^=s[r];            s[r]^=s[l];            s[l]^=s[r];            l++;            r--;        }        return s;    }};
0 0