舉幾個例子觀察
19 = 2*9 +1
9 = 2*4 +1
4 =2*2+0
2=2*1+0
1=2*0+1
---------
20=2*10+0
10=2*5+0
5=2*2+1
2=2*1+0
1=2*0+1
---------
19=10011
20=10100
根據觀察可以得到每次取餘數再加在開頭部分就可以了
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
int c;
string s;
while((cin>>n))
{
s= "";
if(n%2==0)
{
while(n!=0)
{
c = n%2;
n /=2;
if(c == 0)s ='0'+ s;
else s= '1' + s ;
}
cout<<s<<endl;
}
else
{
while(n!=0)
{
c = n%2;
n /=2;
if(c == 0)s = '0'+s ;
else s= '1' + s ;
}
cout<<s<<endl;
}
}
}