Wednesday, July 25, 2012

Amazon Interview Question 2

 write the code ofTwo large numbers ( their integer limits are very large which has not in the integers range) , so give the output of adding the two large numbers?
Example;
str1 ="1111111111111111111111111111111111111111"
 str2 ="22222222222222222222222222222222222222222"
stmstr = "33333333333333333333333333333333333333333"
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

void rev(char s[],int len){
    char tmp;
    len--;
    for(int i = 0; i < len; i++,len--){
        tmp = s[i];
        s[i] = s[len];
        s[len] = tmp;
    }
}

int main(){
    char s1[] = "9984848448485";
    char s2[] = "126";
    char ans[1024];
    int l1,l2,a,b;

    l1 = strlen(s1);
    l2 = strlen(s2);
    rev(s1,l1);
    rev(s2,l2);

    int j = a = 0;
    for(int i = 0; i < l1 || i < l2 || a; i++){
        a += (i < l1)? s1[i] - '0' : 0;
        b = (i < l2)? s2[i] - '0' : 0;
        a += b;
        ans[j++] = (a % 10) + '0';
        a /= 10;
    }
    ans[j] = '\0';

    rev(s1,l1);
    rev(s2,l2);
    rev(ans,j);
    printf("%s + %s = %s\n",s1,s2,ans);

    return 0;
}

No comments:

Post a Comment