LeetCode 八月打卡day3 415. 字符串相加(高精度模拟)

题目链接
在这里插入图片描述

思路:

  • 比较简单的模拟题,判断出哪一个字符串为较长字符串,然后再将短字符串和长字符串一位一位的相加,同时记录进位

代码:

class Solution {
    
    
public:
    string addStrings(string num1, string num2) {
    
    
        string a,b;
        int pos=0;
        if(num1.size()>=num2.size())
        {
    
    
            a=num1;
            b=num2;
        }
        if(num1.size()<num2.size())
        {
    
    
            a=num2;
            b=num1;
        }
        int l1=a.size()-1,l2=b.size()-1;
        while(l2>=0)
        {
    
    
            int temp=a[l1]-'0'+b[l2]-'0'+pos;
            pos=temp/10;
            temp%=10;
            a[l1]=temp+'0';
            l1--;
            l2--;
        }
        while(l1>=0)
        {
    
    
            int temp=a[l1]-'0'+pos;
            pos=temp/10;
            temp%=10;
            a[l1]=temp+'0';
            l1--;
        }
        if(pos>0)
        {
    
    
            string temp=to_string(pos);
            a=temp+a;
        }
        return a;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43663263/article/details/107788249