本文共 1034 字,大约阅读时间需要 3 分钟。
Write a program to print Binary representation of a given number.
This is a simple problem, the reason why it is posted here is because it was a MS Interview question. Obviously, we can do it both in iterative and recursive way.
Iterative way:
1) Let us take number 'NUM' and we want to check whether it's 0th bit is ON or OFF bit = 2 ^ 0 (0th bit) if NUM & bit == 1 means 0th bit is ON else 0th bit is OFF2) Similarly if we want to check whether 5th bit is ON or OFF bit = 2 ^ 5 (5th bit) if NUM & bit == 1 means its 5th bit is ON else 5th bit is OFF.
Recursive way:
step 1) if NUM > 1 a) push NUM on stack b) recursively call function with 'NUM / 2'step 2) a) pop NUM from stack, divide it by 2 and print it's remainder.
Iterative code:
void bin(unsigned n){ unsigned i; for (i = 1 << 31; i > 0; i = i / 2) (n & i)? printf("1"): printf("0");}
recursive code:
void bin(unsigned n){ /* step 1 */ if (n > 1) bin(n/2); /* step 2 */ printf("%d", n % 2);}
转载地址:http://kexti.baihongyu.com/