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 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短