力扣415——字符串相加,进制加法


```cpp
class Solution {
public:
    string addStrings(string num1, string num2) {
        string ans = "";

        //初始位置,从末位开始
        int i = num1.size() - 1;
        int j = num2.size() - 1;

        //表示进位
        int add = 0;

        //注意逻辑连接词为 || ,因为不一定位数相同
        //i,j 往前移动,最终到 i=0,j=0 所以终止条件为 i<0,j<0
        while(i>=0 || j>=0 || add != 0){

            //三目运算符,x,y分别赋值两个数的个位数
            int x =   i>=0 ? num1[i] - '0' : 0;
            int y =   j>=0 ? num2[j] - '0' : 0;

            int result = x+y+add;

            //加 0 可以满足转化为字符串
            //注意这里不是 += ,而是入串
            ans.push_back('0' + result % 10);

            //用求余更改进位值
            add = result /10;

            i --;
            j --;
        }
        //注意反转单词,不要写错
        reverse(ans.begin(),ans.end());

        return ans;
    }
};

同类型题目,稀土掘金
力扣415——字符串相加,进制加法_第1张图片记录bug
报错 error: no type named ‘type’ in ‘struct std::enable_if

一般来讲,该错误发生的原因多为未声明std namespace,但是如果cin、cout时未注意<<或>>此类信息流方向,也会导致报该错误。

报错 error: error: ‘reverse’ was not declared in this scope

需要声明 algorithm 。

#include
#include
#include
#include
using namespace std;

int getInt(char a){
    if(isdigit(a)){
        return a - '0';
    }else{
        return a - 'a' + 10;
    }
}

char getChar(int i){
    if(i >= '0' && i <= '9'){
        return i + '0';
    }else{
        return i + 'a' - 10;
    }
}

int main(){
    string num1;
    string num2;
    cin>>num1>>num2;

    int i = num1.size() - 1;
    int j = num2.size() - 1;
    int add = 0;
    string ans = "";

    while (i>= 0 || j >= 0 || add != 0)
    {
        /* code */
        //将 a 看作 10 ,b 看作 11
        int x = i>= 0 ? getInt(num1[i]) : 0;
        int y = j>=0 ? getInt(num2[j]) : 0;
        int result = x + y + add;
        ans.push_back(getChar(result % 36));
        add = result / 36;
        i --;
        j --;
    }
    reverse(ans.begin(),ans.end());
    cout<<ans;

    return 0;
}

你可能感兴趣的:(力扣)