reference:
http://www.geeksforgeeks.org/binary-representation-of-a-given-number/
Problem Definition:
Write a program to print Binary representation of a given number.
Solution:
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 OFF 2) 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.
Code:
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); }
本文介绍了一种简单的方法来打印给定数字的二进制形式,包括迭代和递归两种实现方式。通过这两种方法,可以有效地确定数字中每一位是否为1或0。
437

被折叠的 条评论
为什么被折叠?



