checking every digit in a number for oddness

Posted by tryt on Stack Overflow See other posts from Stack Overflow or by tryt
Published on 2010-05-25T20:17:15Z Indexed on 2010/05/25 20:21 UTC
Read the original article Hit count: 99

Filed under:

Hello. I was writing a function which checks if every digit in a number is odd. I came accross this weird behaviour. Why does the second function return different (incorrect) results, eventhough its basically the same? (implemented in an opposite way)

#include <stdio.h>

int all_odd_1(int n) {
 if (n == 0) return 0;
 if (n < 0) n = -n;

 while (n > 0) {
  if (n&1 == 1)
     n /= 10;
  else
     return 0;
  }

return 1;
}


int all_odd_2(int n) {
 if (n == 0) return 0;
 if (n < 0) n = -n;

 while (n > 0) {
  if (n&1 == 0)
     return 0;
  else
     n /= 10;
  }

return 1;
}


int main() {

 printf("all_odd_1\n");
 printf("%d\n", all_odd_1(-131));
 printf("%d\n", all_odd_1(121));
 printf("%d\n", all_odd_1(2242));
 printf("-----------------\n");
 printf("all_odd_2\n");
 printf("%d\n", all_odd_2(131));
 printf("%d\n", all_odd_2(121));
 printf("%d\n", all_odd_2(2242));
 return 0;
}

© Stack Overflow or respective owner

Related posts about c