简体   繁体   中英

can I check if a number is odd or even by using add and subract instructions only?

can I check if a number is even or odd by using add and subtraction. I can subtract the number until it get to 2 or 1 but can I do it without that. can i use the neighboring numbers to see if the number is odd or even

Thanks

Okay, you're not specifying which operators you CAN use, but since you mentioned in one comment that you only really abhor division and modulo, I propose this:

if ((number & 1) == 0) {
    // even
} else {
    // odd
}

Quick hack.

#include <assert.h>

// return i << 31 which is != 0 if i is odd
// 32-bit int implementations only;
// not portable, but could be made so -- you get the idea
int odd(int i) {
    assert((1<<31) != 0 && (1<<32) == 0);
    i += i; i += i; i += i; i += i; i += i; i += i; i += i; i += i; 
    i += i; i += i; i += i; i += i; i += i; i += i; i += i; i += i; 
    i += i; i += i; i += i; i += i; i += i; i += i; i += i; i += i; 
    i += i; i += i; i += i; i += i; i += i; i += i; i += i; 
    return i;
}

int main() {
    int i = 0;
    do {
        assert(odd(i) ? (i&1) : !(i&1));
        ++i;
    } while (i != 0);
    return 0;
}

This goes back to grade school actually. Take the last digit. If the last digit is odd, it's odd. If the last digit is even it's even. If you can look at the number in binary format it's even easier.

If you can't convert the number to any non-base 10 format then those are REALLY strange requirements - ie: homework.

Old question, new answer:

    int odd(int val){
        return ((val>>1)<<1) != 0;
    }

Of course you can! You know that even and odd numbers always alternate, so start with 0 and a boolean variable set to true, and count up to your number, flipping a boolean each time you count!

Let's say n = 3

0 - even
1 - odd
2 - even
3 - odd

How you implement this is up to you, but you can even use recursion if you want (this example is in Java):

static boolean isOdd(int number){
    if(number > 0){
        return !isOdd(number-1);
    }else{
        return false;
    }
}

It doesn't work with negative numbers, but why do you even need to use addition and subtraction to check if a number is odd anyway? In the real world, you'd use modulo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM