C/C++教程

[Oracle] LeetCode 415 Add Strings

本文主要是介绍[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;
    }
};
这篇关于[Oracle] LeetCode 415 Add Strings的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!