C Programming - Divisible By 3 or Not (continued)
Some more additions to my previous post C Programming - Divisible By 3 or Not.Code:
1. A solution that I got as a comment to my previous post. Thanks Piyush!
struct NODE {
bool returnValue;
struct NODE *next;
} MOD3_LOOP[3];
bool DivBy3(int n)
{
MOD3_LOOP[0].returnValue = TRUE;
MOD3_LOOP[0].next = &MOD3_LOOP[1];
MOD3_LOOP[1].returnValue = FALSE;
MOD3_LOOP[1].next = &MOD3_LOOP[2];
MOD3_LOOP[2].returnValue = FALSE;
MOD3_LOOP[2].next = &MOD3_LOOP[0];
NODE *iterator = &MOD3_LOOP[0];
int val = n;
while(val != 0) {
for (int i = 0; i < (val & 0x03); i++)
iter = iter->next;
val = val>>2;
}
return (iter->returnValue);
}
2. Another One
int div3(int number)
{
if ( number < 0 ) number = -number;
while ( number > 2 ) {
unsigned int odd = number & 0xaaaaaaaa;
unsigned int even = number & 0x55555555;
int count = 0;
while(odd) {
odd &= (odd-1);
count++;
}
while(even) {
even &= (even-1);
count--;
}
if ( count < 0 ) count = -count;
number = count;
}
return (number == 0);
}
Please post in your comments about these solutions.
0 Comments (Post a Comment)