Precision adder problem A + B

Overview:

1, the number stored in an array of char string;
2, the elements in the array to another array of char into reverse, i.e. a small number of bits on the array in small number, a large number of discharge large number of bits;
3, each character is converted into a char-int numbers, such as '5' - '0' = 5, so put int char into digital numbers;
4, an addition operation between each bit of the carry plus a note;
5, the highest median pay attention to whether there is a carry output one o'clock, if not the most significant bit 0 output;

Emphasis

Steps 2 and 3

The elements in the array to another char array into reverse

Each character is converted into a char type int digital

for (i=len1-1;i>=0;i--){
        s1[(len1-1)-i]=a[i]-'0';
    }
    for (i=len2-1;i>=0;i--){
        s2[(len2-1)-i]=b[i]-'0';
    }

Step 4

An addition operation between each bit

for (i=0;i<max;i++){
        c[i+1]+=(c[i]+s1[i]+s2[i])/10;
        c[i]=(c[i]+s1[i]+s2[i])%10;
        }

Step 5

The highest median pay attention to whether there is output into the one o'clock, if not the most significant bit output 0

if (c[i]!=0){
        for (k=i;k>=0;k--){
            printf("%d",c[k]);
        }
    }
    else {
        for (k=i-1;k>=0;k--){
            printf("%d",c[k]);
        }
    }

The complete code

#include<stdio.h>
#include<string.h>
char a[10007],b[10007];
int s1[10007],s2[10007],c[10007];
int main(){
    scanf("%s",a);
    scanf("%s",b);
    int i; 
    char temp[10007];
    int len1=strlen(a),len2=strlen(b);
    int max=len1>len2?len1:len2;
    for (i=len1-1;i>=0;i--){
        s1[(len1-1)-i]=a[i]-'0';
    }
    for (i=len2-1;i>=0;i--){
        s2[(len2-1)-i]=b[i]-'0';
    }
    for (i=0;i<max;i++){
        c[i+1]+=(c[i]+s1[i]+s2[i])/10;
        c[i]=(c[i]+s1[i]+s2[i])%10;
        }
    int k;
    if (c[i]!=0){
        for (k=i;k>=0;k--){
            printf("%d",c[k]);
        }
    }
    else {
        for (k=i-1;k>=0;k--){
            printf("%d",c[k]);
        }
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/xiao-qingjiang/p/12449096.html