位操作练习

题目描述
给出两个不大于65535的非负整数,判断其中一个的16位二进制表示形式,是否能由另一个的16位二进制表示形式经过循环左移若干位而得到。 循环左移和普通左移的区别在于:最左边的那一位经过循环左移一位后就会被移到最右边去。比如: 1011 0000 0000 0001 经过循环左移一位后,变成 0110 0000 0000 0011, 若是循环左移2位,则变成 1100 0000 0000 0110

输入描述:
每行有两个不大于65535的非负整数

输出描述:
对于每一行的两个整数,输出一行,内容为YES或NO

示例1
输入
2 4
9 18
45057 49158
7 12
输出
YES
YES
YES
NO

题目解析:首先数字不大于65535在机器的整数表示范围内,但是为了方便循环移动,有两种方法,将整数的每位保存或者表示为字符串,方便前后添加和删除。数字由16位标识,所以1表示为0000000000000001。要将转化为2进制的数字,补足16位。

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<iomanip>
#include<map>
#include<set>
#include<vector>

using namespace std; 
void rush(vector<int> &p,int a){
    while(a!=0){
        p.insert(p.begin(),a%2);
        a/=2;
    }
}
 
int main(){
    int x,y;
    while(cin >> x >> y){
        vector<int> p,q;
        rush(p,x);   //转化为2进制 
        rush(q,y);
        while(p.size()<16){   //65535最多有 16个1,所以不够位的补零 
            p.insert(p.begin(),0);
        }
        while(q.size()<16){
            q.insert(q.begin(),0);
        }
        bool flag=false;
        for(int i=0;i<p.size();i++){
            int temp=p[0];
            p.erase(p.begin());  //erase擦除的是指针 
            p.push_back(temp); //进vector之后会被放在最后面,所以可以实现循环
            if(p==q){   //只有int可以这样比 
                flag=true;
            }
        }
        if(flag==true){
        	cout << "YES" << endl;
    	}else{
    		cout << "NO" << endl;
		}
    }
    return 0;
}

/*

#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std; 

string convert(int n){    //转换二进制 
	string newstr;
	while(n > 0){
		newstr += char((n % 2) + '0');
		n /= 2;
	}
	reverse(newstr.begin() , newstr.end());
	return newstr;
}

string complete(int n){   //补全16位数 
	string str = convert(n);
	if(str.size() < 16){
		int t = 16 - str.size();
		for(int i = 0 ; i < t ; i++){
			str.insert(0 , "0");
		}
	}
	return str;
}
int main(){
	int a,b;
	while(cin >> a >> b){
		string str1 = complete(a);
		string str2 = complete(b);
		bool flag = false;
		for(int i = 0; i < str1.size(); i++){   //判断 
			char temp = str1[0];
			str1 = str1.substr(1,str1.size() - 1);
			str1 += temp;
			if(str1 == str2){
				flag = true;
				break;
			}
		}
		if(flag){
			cout << "YES" << endl;
		}else{
			cout << "NO" <<endl;
		}
	}
	return 0;
}
*/ 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值