博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Binary representation of a given number
阅读量:4151 次
发布时间:2019-05-25

本文共 1034 字,大约阅读时间需要 3 分钟。

reference: 

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 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.

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);}
 

转载地址:http://kexti.baihongyu.com/

你可能感兴趣的文章
JavaScript substr() 方法
查看>>
JavaScript slice() 方法
查看>>
JavaScript substring() 方法
查看>>
HTML 5 新的表单元素 datalist keygen output
查看>>
(转载)正确理解cookie和session机制原理
查看>>
jQuery ajax - ajax() 方法
查看>>
将有序数组转换为平衡二叉搜索树
查看>>
最长递增子序列
查看>>
从一列数中筛除尽可能少的数,使得从左往右看这些数是从小到大再从大到小...
查看>>
判断一个整数是否是回文数
查看>>
经典shell面试题整理
查看>>
腾讯的一道面试题—不用除法求数字乘积
查看>>
素数算法
查看>>
java多线程环境单例模式实现详解
查看>>
将一个数插入到有序的数列中,插入后的数列仍然有序
查看>>
在有序的数列中查找某数,若该数在此数列中,则输出它所在的位置,否则输出no found
查看>>
万年历
查看>>
作为码农你希望面试官当场指出你错误么?有面试官这样遭到投诉!
查看>>
好多程序员都认为写ppt是很虚的技能,可事实真的是这样么?
查看>>
如果按照代码行数发薪水会怎样?码农:我能刷到公司破产!
查看>>