zoukankan      html  css  js  c++  java
  • Death to Binary? (模拟)题解

    思路:

    除去前导0,注意两个1不能相邻(11->100),注意 0 *** 或者*** 0或者0 0情况

    用string的reverse()很舒服

    代码:

    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<cctype>
    #include<queue>
    #include<cmath>
    #include<string>
    #include<map>
    #include<stack> 
    #include<set>
    #include<vector>
    #include<iostream>
    #include<algorithm>
    #define INF 0x3f3f3f3f
    #define ll long long
    const int N=50;
    const int MAX=45;
    const int MOD=1000; 
    using namespace std;
    ll fib[N];
    void initfib(){
    	fib[0]=1;fib[1]=2;
    	for(int i=2;i<=MAX;i++){
    		fib[i]=fib[i-1]+fib[i-2];
    	}
    } 
    void change(ll sum,string &c){
    	c.clear();
    	int j;
    	for(j=MAX;j>=0;j--){
    		if(sum>=fib[j]) break;
    	}
    	for(int i=j;i>=0;i--){
    		if(sum>=fib[i]){
    			sum-=fib[i];
    			c+='1';
    		}
    		else c+='0';
    	}
    	if(c.length()==0) c='0';
    }
    int main(){
    	initfib();
    	string a,b,c;
    	ll A,B,sum;
    	while(cin>>a>>b){
    		reverse(a.begin(),a.end());
    		reverse(b.begin(),b.end());
    		A=B=0;
    		for(int i=0;i<a.length();i++){
    			if(a[i]=='1') A+=fib[i];
    		}
    		ll cut=0,n;
    		n=a.length()-1;
    		while(1){
    			if(a[n]=='1') break;
    			if(a[n]=='0') cut++;
    			n--;
    		}
    		a=a.substr(0,a.length()-cut);	//去掉a前导0 
    		reverse(a.begin(),a.end());
    		
    		for(int i=0;i<b.length();i++){
    			if(b[i]=='1') B+=fib[i];
    		}
    		cut=0;
    		n=b.length()-1;
    		while(1){
    			if(b[n]=='1') break;
    			if(b[n]=='0') cut++;
    			n--;
    		}
    		b=b.substr(0,b.length()-cut);	//去掉b前导0 
    		reverse(b.begin(),b.end());
    
    		sum=A+B;
    		change(A,a);
    		change(B,b);
    		change(sum,c);
    
    		int mxlen=max(a.length(),max(b.length(),c.length()));
    		cout<<"  ";
    		for(int i=0;i<mxlen-a.length();i++) cout<<" ";
    		cout<<a<<endl;
    		cout<<"+ ";
    		for(int i=0;i<mxlen-b.length();i++) cout<<" ";
    		cout<<b<<endl;
    		cout<<"  ";
    		for(int i=0;i<mxlen;i++) cout<<"-";
    		cout<<endl;
    		cout<<"  ";
    		for(int i=0;i<mxlen-c.length();i++) cout<<" ";
    		cout<<c<<endl<<endl;
    	} 
    	return 0;
    }

  • 相关阅读:
    小米手机导出微信聊天记录
    IBM X3650 M4 微码升级(BIOS升级)
    leetcode1987 不同的好子序列数目
    leetcode1932 合并多棵二叉搜索树
    leetcode146 LRU 缓存机制
    leetcode456 132 模式
    leetcode316 去除重复字母
    GIT放弃本地所有修改,强制拉取更新
    vendor/easywechat-composer/easywechat-composer/src:
    微信公众号推广饿了么赏金红包制作
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9409111.html
Copyright © 2011-2022 走看看