给定数字的二进制表示形式的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<<"The number is "<<n<<" and its binary representation is ";
tobinary(n);
n = 12;
cout<<"\nThe number is "<<n<<" and its binary representation is ";
tobinary(n);
}输出
The number is 6 and its binary representation is 110 The number is 12 and its binary representation is 1100
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP