給定數字的二進位制表示形式的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
廣告