Một số nhị phân là một số chỉ bao gồm hai chữ số 0 và 1. Ví dụ:01010111.
Có nhiều cách khác nhau để biểu diễn một số nhất định ở dạng nhị phân.
Phương thức đệ quy
Phương thức này được sử dụng để biểu diễn một số ở dạng nhị phân của nó bằng cách sử dụng đệ quy.
Thuật toán
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.
Ví dụ
#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);
} Đầu ra
The number is 6 and its binary representation is 110 The number is 12 and its binary representation is 1100