十進制整數轉化爲二進制數

/*
Jennifer
2018年2月2日17:09:12-2018年2月2日17:50:53
題目內容:
將十進制整數轉換爲二進制數
輸入描述:輸入數據中含有不多於50個的整數n
輸出描述:對於每個n,以11位的寬度右對齊輸出n值,然後輸出"-->",再然後輸出二進制數。每個整數n的輸出,獨立佔一行。
輸入樣例:
2
0
-12
1
輸出樣例:
       2-->10
       0-->0
      -12-->-1100
      1-->1
*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string s;
int main()
{
    int n;
    while(cin>>n)
    {
        if(n == 0)
        {
            cout<<"          0-->0"<<endl;
            continue;
        }
        s = "";
        for(int a=n;a;a=a/2)
        {
            s = s + (a%2?'1':'0');
        }
        std::reverse(s.begin(),s.end());
        const char *sss = s.c_str();
        cout.width(11);
        cout<<n<<(n<0?"-->-":"-->")<<sss<<endl;
    }
    return 0;
}

發佈了47 篇原創文章 · 獲贊 29 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章