• 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;
    }

  • 相关阅读:
    python中numpy的用法
    基于逻辑回归识别坐标是否在第一象限
    python变量,函数
    DOM的核心总结
    节点操作
    自定义属性操作
    排他思想及部分案例
    事件基础及操作元素
    获取元素
    DOM 介绍
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9409111.html
Copyright © 2020-2023  润新知