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