zoukankan      html  css  js  c++  java
  • zzulioj 2624: 小H的奇怪加法(模拟)

    题目链接:http://acm.zzuli.edu.cn/problem.php?id=2624 

      模拟加法进位就行了,写起来和高精度加法类似。

    #include<set>
    #include<map>
    #include<stack>
    #include<queue>
    #include<cmath>
    #include<cstdio>
    #include<cctype>
    #include<string>
    #include<vector>
    #include<climits>
    #include<cstring>
    #include<cstdlib>
    #include<iostream>
    #include<algorithm>
    #define max(a, b) (a > b ? a : b)
    #define min(a, b) (a < b ? a : b)
    #define mst(a) memset(a, 0, sizeof(a))
    #define _test printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
    using namespace std;
    typedef long long ll;
    typedef pair<int, int> P;
    const double eps = 1e-7;
    const int INF = 0x3f3f3f3f;
    const ll ll_INF = 0x3f3f3f3f3f3f3f;
    const int maxn = 1e3+10;
    char ls[20];
    char num1[maxn], num2[maxn], res[maxn];
    void add() { //高精度整数加法(改)
        mst(res);
        int len1 = strlen(num1);
        int len2 = strlen(num2);
        int len3 = strlen(ls);
        reverse(num1, num1+len1);
        reverse(num2, num2+len2);
        int len, carry;
        len = carry = 0;
        for (int i = 0; i<len1 || i<len2; ++i) {
            carry += i<len1 ? num1[i] - '0' : 0;
            carry += i<len2 ? num2[i] - '0' : 0;
            if (ls[len3-i-1] != '0') { //非0即为2~9进制
                res[len] = carry%(ls[len3-i-1]-'0') + '0';
                carry /= (ls[len3-i-1] - '0');
            }
            else { //是0就按10进制
                res[len] = carry%10 + '0';
                carry /= 10;
            }
            ++len;
        }
        if (carry) //判断最后一位是不是有进位
            res[len++] = carry + '0';
        res[len] = 0;
        for (int i = len-1; i>0; --i) { //排除先导0的影响 注意 不能直接i>=0, 如果结果刚好等于0就会出错了
            if (res[i] == '0')
                res[i] = 0;
            else 
                break;
        }
        reverse(res, res+strlen(res));
    }   
    int main(void) {
        scanf("%s %s %s", ls, num1, num2);
        add();
        printf("%s\n", res);
        return 0;
    }
  • 相关阅读:
    Introduce myself
    二叉搜索树的后序遍历序列(剑指offer-23)
    从上到下打印二叉树(剑指offer-22)
    二叉树的深度(剑指offer-38)
    不用加减乘除做加法(剑指offer-48)
    栈的压入、弹出序列(剑指offer-21)
    Java容器
    包含min函数的栈(剑指offer-20)
    在Docker中创建Mongodb数据库
    词向量聚类实验
  • 原文地址:https://www.cnblogs.com/shuitiangong/p/12078740.html
Copyright © 2011-2022 走看看