hiho一下157

二进制小数

题意:给一个小于1的小数,输出该小数的二进制表示,如果是无限的输出NO

思路:知道小数二进制的转换后直接,大数乘法xjb模拟就是了

AC代码:

#include "iostream"
#include "string.h"
#include "stack"
#include "queue"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "algorithm"
#include "stdio.h"
#include "math.h"
#define ll long long
#define bug(x) cout<<x<<" "<<"UUUUU"<<endl;
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
const int N=1e5+100;

char ch[N],ans[N];
string s,a,b,ss;
map<int,int> M;
string Multiply(string s,int x){
    reverse(s.begin(),s.end());
    int cmp=0;
    for(int i=0;i<s.size();i++){
        cmp=(s[i]-'0')*x+cmp;
        s[i]=(cmp%10+'0');
        cmp/=10;
    }
    while(cmp){
        s+=(cmp%10+'0');
        cmp/=10;
    }
    reverse(s.begin(),s.end());
    return s;
}
int BKDRHash(string s){
    long long seed=131;
    long long hash=0;
    int i = 0;
    while(i<s.size()&&s[i]) hash=hash*seed+(s[i++]);
    return (hash & 0x7FFFFFFF);
}

int main(){
    int t;
    cin>>t;
    while(t--){
        cin>>ch;
        s=ch+2;
        ans[0]='0',ans[1]='.';
        int l=1,flag=0;
        if(s[s.size()-1]!='5') flag=1;
        M.clear();
        while(s.size()>0){
            int ha=BKDRHash(s);
            if(M[ha] || flag){
                flag=1;
                break;
            }
            M[ha]=1;
            int l0=s.size();
            s=Multiply(s,2);
            int l1=s.size();
            int f=0;
            for(int i=0; i<s.size(); ++i){
                if(s[i]!='0'){
                    f=1;
                    break;
                }
            }
            if(f){ //cout<<ss.size()<<" "<<s.size()<<endl;
                if(l1<=l0)
                    ans[++l]='0';
                else{
                    ans[++l]=s[0];
                    s.erase(0,1);
                }
            }
            else break;
        }
        ans[++l]='\0';
        if(flag) cout<<"NO\n";
        else cout<<ans<<endl;
    }
    return 0;
}
/*
3
0.5
0.75
0.3
*/

 

posted on 2017-07-01 22:01  lazzzy  阅读(110)  评论(0编辑  收藏  举报

导航