Friday, January 30, 2009

UVa problem 10469: sample algorithm, sample code

To solve 10469 (To carry or not to carry), one needs to be able to discover that in order to get the sum without the carry-bits, one simply has to perform a bitwise xor operation on the two numbers.

XOR is simply the following formulat:
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 1

For example, for 4 XOR 6, we have to represent them in binary as follows:
4: 100
6: 110
______
2: 010


001 #include "stdio.h"
002
003 int main() {
004 char line[100];
005
006 int i, j;
007
008 while (fgets(line, 100, stdin)) {
009 sscanf(line, "%d %d", &i, &j);
010 printf("%d\n", i ^ j);
011 }
012
013 return 0;
014 }

No comments:

Post a Comment