C/C++ 超長正整數相加

本題整體思想不難,主要是想好用什麼容器去存儲計算值和計算結果值,這裏用的是字符串,當然也可以用數組,題目鏈接:https://www.nowcoder.com/practice/5821836e0ec140c1aa29510fd05f45fc?tpId

以下爲解答代碼(具體細節看註釋):

string AddLongInteger(string addend, string augend){
    int i = 0,n=addend.size()>augend.size()?n=addend.size():n=augend.size();  //n爲較長計算值的長度,用來循環計算時使用
    string c;              //計算結果保存的值
    int  temp, tep = 0;         //進位值要記得初始化
    reverse(addend.begin(), addend.end());         //這裏將兩個加數都翻轉過來計算,主要是爲了寫入結果的時候可以直接使用‘+=’
    reverse(augend.begin(), augend.end());         //當然也可以沒有這一步,直接從後往前算
    for (; i < n; i++){
        int a = i<addend.size() ? addend[i] - '0' : 0;         //若是一個加數已經全部計算完成,在接下來就用0代替來計算
        int b = i<augend.size() ? augend[i] - '0' : 0;
        temp = (a+b+tep)% 10;           //計算結果值(要填入結果的值)
        tep = (a + b + tep) / 10;   //進位值
        c += temp + 48;  // 填入結果
    }
    if (tep>0){    //若是最後一位計算有進位值,則直接填入結果
        c += tep+'0';
    }
    reverse(c.begin(), c.end());   //將計算結果反過來就是正確結果
    return c;
}

int main(){
    string a, b, c;
    while (cin >> a >> b){
        cout << AddLongInteger(a, b) << endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章