zoukankan      html  css  js  c++  java
  • 大整数加法 HDU1002

    今天早上没事干又把这个敲了一遍,虽然手冻得不行,不过又深入理解理解还可以哈。

    难点就在给你的整数可能很大很长,所以long long 肯定不行,得用字符串来读取存储,然后注意一下相加的时候进位,最后输出注意去0就OK啦。(核心思想就是大数逆序相加最后逆序再输出就是正确结果了)。然后下边是自己写的思路比较清晰的代码,大家可以借鉴后再自己想想有没有更简单的,可以互相学习呀。

    #include<stdio.h>
    #include<string.h>
    #include<math.h>
    #include<algorithm>
    using namespace std;
    char A[1005],B[1005];
    int a[1005],b[1005],c[2002];
    void nuxu()//简单的逆序存入整型数组
    {
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        memset(c,0,sizeof(c));
        int k1=0,k2=0,ans;
        ans=strlen(A);
        for(int i=ans-1;i>=0;i--)
            a[k1++]=A[i]-'0';
        ans=strlen(B);
        for(int i=ans-1;i>=0;i--)
            b[k2++]=B[i]-'0';
    }
    void yunsuan()
    {
        int k=strlen(A)>strlen(B)?strlen(A):strlen(B);
        int len=0;
        for(int i=0;i<k;i++)
        {
            c[i]+=a[i]+b[i];
            if(c[i]>9)//进位操作,为什么只用判一次,或者说只进位一次大家再自己想想啦;
            {
                c[i+1]++;
                c[i]-=10;
            }
        }
    }
    int main()
    {
        int t,flag;
        scanf("%d",&t);
        for(int j=1;j<=t;j++)
        {
            flag=0;
            if(j!=1)
                printf("
    ");//题目要求格式
            scanf("%s%s",A,B);
            nuxu(); //写main函数外边更清晰,简便点
            yunsuan();
            printf("Case %d:
    %s + %s = ",j,A,B);//以上是题目要求输出格式
            for(int i=1000;i>=0;i--)//逆序输出
            {
                if(c[i]!=0||flag==1)//直接控制去前导0了
                {
                    printf("%d",c[i]);
                flag=1;
                }
            }
            printf("
    ");
        }
    }
  • 相关阅读:
    ABAP接口用法
    监听textarea数值变化
    The first step in solving any problem is recognizing there is one.
    Wrinkles should merely indicate where smiles have been.
    God made relatives.Thank God we can choose our friends.
    Home is where your heart is
    ABAP跳转屏幕
    Python 工具包 werkzeug 初探
    atom通过remote ftp同步本地文件到远程主机的方法
    Mongodb学习笔记一
  • 原文地址:https://www.cnblogs.com/nr1999/p/8443801.html
Copyright © 2011-2022 走看看