微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Oracle] LeetCode 415 Add Strings

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Solution

其实就是高精度加法,这里按照竖式加法即可,其中 \(top\) 表示进位

点击查看代码
class Solution {
private:
    string ans="";
    
public:
    string addStrings(string num1, string num2) {
        int n1 = num1.size();
        int n2 = num2.size();
        int top = 0;
        int pos1=n1-1, pos2=n2-1;
        while(1){
            int s1=0, s2=0;
            if(pos1>=0)s1=num1[pos1]-'0';
            if(pos2>=0)s2=num2[pos2]-'0';
            int sum = s1+s2+top;
            if(sum<10){
                ans= char('0'+sum)+ans; top=0;
            }
            else{
                ans= char(sum%10+'0')+ans;top=1;
            }
            pos1--;pos2--;
            if(pos1<0 && pos2<0) break;
        }
        if(top){
            ans=char('0'+top)+ans;
        }
        //reverse(ans.begin(), ans.end());
        return ans;
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐