Leetcode--字符串相加 C++实现

题目: 415. 字符串相加

题目描述:

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

思路:

  1. 使用数值相加减的思路,从后向前按位相加
  2. 设置一个进位next
  3. 相加后的每一位进行尾插
  4. 最后对字符串进行逆置,得到结果
class Solution {
    
    
public:
    string addStrings(string num1, string num2) {
    
    

        string ret;//定义一个string类
        int end1 = num1.size() - 1, end2 = num2.size()-1;
        int next = 0;//进位的初始值置0
        while(end1 >= 0 || end2 >= 0)//两个字符串都遍历结束,结束循环
        {
    
    
            int x1 = 0, x2 = 0;
            if(end1 >= 0)
            {
    
    
                x1 = num1[end1] - '0';
                --end1;
            }
            if(end2 >= 0)
            {
    
    
                x2 = num2[end2] - '0';//注意数值和字符ASCALL码值的转换
                --end2;
            }

            char retch =x1 + x2 + next;
            if(retch >= 10)//判断进位的值
            {
    
    
                retch -= 10;
                next = 1;
            }
            else
            {
    
    
                next = 0;
            }

            ret += (retch + '0');//尾插,但是不能直接+retch,需要加它的ASCAll码值 
        }
        if(next == 1)//当两串字符都走到第0位,还需判断进位的值是否为1,如 9999 + 1 
        ret += '1';
        reverse(ret.begin(), ret.end());//字符串
        return ret;
    }
};

注意:字符的加减是ASCALL码值的加减

猜你喜欢

转载自blog.csdn.net/du1232/article/details/115446248