zoukankan      html  css  js  c++  java
  • acwing792. 高精度减法

    给定两个正整数(不含前导 0),计算它们的差,计算结果可能为负数。

    输入格式

    共两行,每行包含一个整数。

    输出格式

    共一行,包含所求的差。

    数据范围

    1≤整数长度≤10^5

    输入样例:

    32
    11
    

    输出样例:

    21
    

    方法一:

    模拟手算

    先把数字的低位和高位互换,变成个位在下标0处,比较好写。注意最后高位的无效0不要输出

    #include <bits/stdc++.h>
    using namespace std;
    
    char a[100010], b[100010];
    
    int main() {
        scanf("%s%s", &a, &b);
        int la = strlen(a) - 1, lb = strlen(b) - 1;
        char *ta = a, *tb = b;
    
        if (lb > la || lb == la && strcmp(a, b) < 0) {
            printf("-");
            swap(ta, tb);
            swap(la, lb);
        }
        // invert
        for (int i = 0; i <= la/2; i++) swap(ta[i], ta[la-i]);
        for (int i = 0; i <= lb/2; i++) swap(tb[i], tb[lb-i]);
    
        int c = 0, p, i;
        for (i = 0; i <= lb; i++) {
            p = ta[i] - tb[i] - c;
            c = p < 0; if (p < 0) p += 10;
            ta[i] = p + '0';
        }
        while (i <= la && c) {
            p = ta[i] - c - '0';
            c = p < 0; if (p < 0) p += 10;
            ta[i] = p + '0';
            i++;
        }
    
        while (la > 0 && ta[la] == '0') la--;
        for (; la >= 0; la--) printf("%c", ta[la]);
    }
    
  • 相关阅读:
    跨数据库操作
    Windows 服务
    Linq To DataTable
    嵌入式软件应用程序开发框架浅见
    31.获取当前系统时间
    30 System类
    29. StringBuilder
    28. string类中方法练习
    27 string类中常用的方法列表
    26.String类(1)
  • 原文地址:https://www.cnblogs.com/nosae/p/15821732.html
Copyright © 2011-2022 走看看