C ++中给定数字的二进制表示
二进制数是仅由两位数字0和1组成的数字。例如01010111。
有多种方式来表示给定数字的二进制形式。
递归方法
此方法用于使用递归以二进制形式表示数字。
算法
Step 1 : if number > 1. Follow step 2 and 3. Step 2 : push the number to a stand. Step 3 : call function recursively with number/2 Step 4 : pop number from stack and print remainder by dividing it by 2.
示例
#include<iostream>
using namespace std;
void tobinary(unsigned number){
if (number > 1)
tobinary(number/2);
cout << number % 2;
}
int main(){
int n = 6;
cout<<"数字 "<<n<<" 其二进制表示为 ";
tobinary(n);
n = 12;
cout<<"\n数字 "<<n<<" 其二进制表示为 ";
tobinary(n);
}输出结果
数字 6 其二进制表示为 110 数字 12 其二进制表示为 1100
热门推荐
10 老师给家长祝福语简短
11 八一祝福语简短文字
12 用名字做祝福语简短
13 古风祝福语 唯美简短端午
14 六一祝福语简短网名
15 情侣520的祝福语简短
16 美好的毕业祝福语简短
17 冬至祝福语简短情话高级
18 女儿要生了祝福语简短