十进制转二进制
思路:所谓的“除二取余”,一个数n先取余数,所得余数为最低位,然后除以二再取余数,所得余数为次低位,以此类推直到n == 1
,再加一个1
为最高位即可
#include <iostream>
#include <string>
using namespace std;
void dec_to_bin(unsigned int n){
if(n == 0){
cout << 0 << endl;
return;
}
int remainder;
string s;
while(n != 1){
remainder = n % 2;
n = n / 2;
if(remainder == 0)
s = s + '0';
else s = s + '1';
}
s = s + '1';
for(int i = s.size() - 1; i >= 0; i--){
cout << s[i];
}
cout << endl;
}
int main(){
unsigned int n;
while(cin >> n){
dec_to_bin(n);
}
return 0;
}