寝癖頭の解法

学習中の覚え書きを投稿、更新していきます。

Aizu Online Judge in C++ #Volume2 - 0220 : Binary Digit A Doctor Loved

Aizu Online Judge(AOJ)の過去問から、その提出コードの解答例です。

・問題 "Binary Digit A Doctor Loved"
https://onlinejudge.u-aizu.ac.jp/problems/0220
・博士の愛した2進数
僕が作成、提出したコードは、以下のとおりです。

・Aizu Online Judge in C++ #Volume2 - 0220 : Binary Digit A Doctor Loved
/*
Aizu Online Judge in C++ #Volume2 - 0220 : Binary Digit A Doctor Loved
 https://onlinejudge.u-aizu.ac.jp/problems/0220
 提出コードの解答例
 https://neguse-atama.hatenablog.com
*/
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
int main(void){
    double n;
    while(cin>>n,n>0){
        string s;
        for(double j,i=128;i>0.03125;i/=2){
            s+=(ll)(j=n/i)+'0';
            if(j>=1){
                n-=i;
            }
            if(i==1){
                s+='.';
            }
        }
        if(n>0){
            cout<<"NA\n";
        }else{
            cout<<s<<endl;
        }
    }
    return 0;
}

設問の出典は、プログラミング問題のオンライン採点システム「Aizu Online Judge(AOJ)」です。
http://judge.u-aizu.ac.jp/onlinejudge/