高中生程式解題系統:二進位制轉換 Binary to Decimal

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

題目連結 http://zerojudge.tw/ShowProblem?problemid=a034

方法如下:
建立空字串 str
當 n > 0 時
   若 n % 2 的結果 加到 str 最前面。
   n = n / 2
輸出 str 

程式碼:

#include <iostream>
using namespace std;
int main()
{
int n;
while(cin >> n)
{
string msg;
while( n > 0)
{
if( n % 2 == 1 )
msg.insert(0, "1");
else
msg.insert(0, "0");
n = n / 2;
}
cout << msg << endl;
}
return 0;
}
view raw a034.cpp hosted with ❤ by GitHub

沒有留言: