二進位出現的1與0就是十進位轉二進位的過程中,每次除以二的mod值,所以可以不用紀錄二進位轉換結果,一直除然後把有1的情況加起來就好了。
十六進位轉二進位也是一樣,先把十六進位換成十進位,然後一直除2。
程式碼:
#include <iostream> #include <cmath> using namespace std; int main() { int t,n; cin>>t; for(int i=0;i<t;i++) { int b1=0,copy,b2=0; cin>>n; copy=n; while(copy>0) { b1+=copy%2; copy/=2; } copy=n; int times=0,x2=0; while(copy>0) { x2+=pow(16,times)*(copy%10); times++; copy/=10; } copy=x2; while(copy>0) { b2+=copy%2; copy/=2; } cout<<b1<<" "<<b2<<endl; } return 0; }
沒有留言:
張貼留言