实现 9 进制加法

Tag: 笔试算法题 Posted on 2022-03-17 19:04:34 Edited on 2022-03-17 19:04:45 Views: 137

概述

实现 9 进制加法

解法

当前解法不支持负数。

#include <bits/stdc++.h>
using namespace std;

string add(string& a, string& b, bool& carry) {
    string res = a;
    carry = false;
    int sz = a.size();
    for (int i = sz - 1; i >= 0; i --) {
        int c = a[i] - '0' + b[i] - '0' + carry;
        if (c >= 9) {
            c %= 9;
            carry = true;
        } else {
            carry = false;
        }
        res[i] = c + '0';
    }
    return res;
}


int main() {
    string a, b; cin >> a >> b;
    string a1, a2, b1, b2;
    bool past = false;
    for (auto c : a) {
        if (c == '.') {
            past = true;
            continue;
        }
        if (past) {
            a2 += c;
        } else {
            a1 += c;
        }
    }
    past = false;
    for (auto c : b) {
        if (c == '.') {
            past = true;
            continue;
        }
        if (past) {
            b2 += c;
        } else {
            b1 += c;
        }
    }
    int sz = int(a1.size()) - int(b1.size());
    string pad(abs(sz), '0');
    if (sz < 0) {
        a1 = pad + a1;
    } else if (sz > 0) {
        b1 = pad + b1;
    }
    sz = int(a2.size()) - int(b2.size());
    string pad2(abs(sz), '0');
    if (sz < 0) {
        a2 += pad2;
    } else if (sz > 0) {
        b2 += pad2;
    }
    bool carry = false;
    string r2 = add(a2, b2, carry);
    string c1(a1.size(), '0');
    if (carry) {
        c1.back() = '1';
    }
    carry = false;
    bool carry2 = false;
    string r1 = add(a1, b1, carry2);
    r1 = add(r1, c1, carry);
    string ans = ((carry || carry2) ? "1" : "") + r1 + '.' + r2;
    cout << ans << endl;
}

未经允许,禁止转载,本文源站链接:https://iamazing.cn/