[OCLUG-devel] calculations one digit at a time
Michael Elkins
michael.elkins at gmail.com
Sun Jul 11 11:18:46 PDT 2004
On Sun, 11 Jul 2004 09:27:44 -0700, James Colannino <james at colannino.org> wrote:
> Hey everyone. I'm trying to figure out how I'm going to do calculations
> working with one digit at a time (this is so that I can work with fixed
> digit numbers.) For example:
Are you doing this as a programming exercise? I'm trying to figure
out why you would want to do integer arithmetic this way?
>
> 110 + 100
>
> First, the two 0's in the one's place would be added, then the 0 and the
> 1 in the tens place, and finally the two 1's in the hundreds place. At
> first glance, it doesn't seem like it would be too difficult. I would
> assign each individual digit to its own variable and go from there. The
> problem is, if I add two numbers and I get a number that's equal to 10
> or greater, I'll have to figure out how to borrow, and I'm not quite
> sure how to do that in C.
I believe you mean carry.
> For example:
>
> 732 + 298
>
> 8 + 2 is 10, so I would have to move the 1 digit in the tens place over
> one. Would I maybe convert 10 into a string, split it into the 1 and 0,
> and then convert both back into integers and add them to their
> appropriate places?
>
> I hope I'm not too out there with my solution :-P I'm just not quite
> sure what I should do.
Off the top of my head, I'd say to represent each digit as an element
in an array, in reverse order such that index 0 is the ones place, 1
is the tens place, etc. Then doing carries is pretty easy:
char a[10]; //operand
char b[10]; //operand
char c[11] = {0}; //result
for (i=0; i<10; i++) {
c[i] = a[i] + b[i];
if (c[i] >= 10) {
c[i+1]++;
c[i] -= 10;
}
}
-Michael
More information about the OCLUG-devel
mailing list