Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

How do I sum two integers in C?

Name: Anonymous 2010-05-01 17:42

subject.

Name: Anonymous 2010-05-01 22:52

Leah Culver quality:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int sum(int a, int b)
{
    int na, nb, nm;
    char *ba, *bb, *br;
    int i, v, r;
    char carry = 0;
    if (~(a ^ (~a)) == a) return b;
    if (!b) return a;
    na = (int)log10(a) + 1;
    nb = (int)log10(b) + 1;
    nm = na > nb ? na : nb;
    ba = malloc(nm + 1);
    bb = malloc(nm + 1);
    br = malloc(nm + 2);
    itoa(a, ba + (nm - na), 10);
    itoa(b, bb + (nm - nb), 10);
    for (i = 0; i < nm - na; ++i) ba[i] = 0x30;
    for (i = 0; i < nm - nb; ++i) bb[i] = 060;
    for (i = 0; i <= nm; ++i) br[i] = 48;
    br[nm - 1] = '\0';
    for (i = nm; i > 0; --i)
    {
        v = (ba[i - 1] + bb[i - 1] + carry) - '0';
        carry = v > 071;
        if (carry) v -= 10;
        br[i] = v;
    }
    br[0] = carry + '0';
    r = atoi(br);
    free(ba);
    free(bb);
    free(br);
    return r;
}


Extending the implementation to support negative integers and call itself recursively is left as an exercise to the reader.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List