UVA 12898 AND OR

Thinking: Having read the scale of number A and B, we know that we should use type long long int. And it is not realistic to use a loop to find the answer like what is described in the problem. What we need to do is to write down some example and try them out. After that, try to find the regulation implied. 

First, convert A and B into binary numbers. Then count how many digits they have. 

If #digitA < #digitB:

ans_AND = 0;

ans_OR = 2^(#digitB)-1;

if #digitA == #digitB:

from the MSB to LSB,

if there is a bit that is different between A and B, break immediately. And from that on, for ans_AND, all bits after the break point become 0, for ans_OR,all bits after the break point become 1.


AC code:

#include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<string>
#include<algorithm>
#include<cmath>
#include<stack>
#include<queue>
#define LLI long long int
using namespace std;
int count_bits(LLI N)
{
	int ans = 0;
	while (N != 0)
	{
		N >>= 1;
		ans++;
	}
	return ans;
}



int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int T;
	LLI A, B;
	scanf("%d", &T);
	for (int t = 1; t <= T; t++)
	{
		scanf("%lld%lldd", &A, &B);

		LLI OR, AND;
		int lena = count_bits(A);
		int lenb = count_bits(B);
		if (lena != lenb)
		{
			OR = (LLI)pow(2, lenb) - 1;
			AND = 0;
		}
		else
		{
			
			int count = 0;
			while (A!=B)
			{
				A >>= 1;
				B >>= 1;
				count++;
			}
			AND = A << count;
			OR = AND + (LLI)pow(2, count) - 1;
		}
		printf("Case %d: %lld %lld\n", t, OR, AND);
	}

	return 0;

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值