LightOJ 1042 - Secret Origins(数论&进制转换)

本文介绍了一个算法挑战:给定一个整数N,找到紧随其后的最小整数,该整数的二进制表示中1的数量与N相同。文章提供了实现这一功能的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This is the tale of Zephyr, the greatest time traveler theworld will never know. Even those who are aware of Zephyr's existence know verylittle about her. For example, no one has any clue as to which time period sheis originally from.

But we do know the story of the first time she set out tochart her own path in the time stream. Zephyr had just finished building hertime machine which she named - "Dokhina Batash". She was making thefinal adjustments for her first trip when she noticed that a vital program wasnot working correctly. The program was supposed to take a number N, andfind what Zephyr called its Onoroy value.

The Onoroy value of an integer N is the number of onesin its binary representation. For example, the number 13 (11012) hasan Onoroy value of 3. Needless to say, this was an easy problem for the greatmind of Zephyr. She solved it quickly, and was on her way.

You are now given a similar task. Find the first numberafter N which has the same Onoroy value as N.

Input

Input starts with an integer T (≤ 65),denoting the number of test cases.

Each case begins with an integer N (1 ≤ N ≤109).

Output

For each case of input you have to print the case number andthe desired result.

Sample Input

Output for Sample Input

5

23

14232

391

7

8

Case 1: 27

Case 2: 14241

Case 3: 395

Case 4: 11

Case 5: 16

 题意

给一个数,把它转换成二进制。找到一个比它大且二进制1的个数与之一样的最小数。

思路

把这个数拆成二进制,找到第一个01,再把01颠倒成10,之后所有1全丢在最后几位。然而我代码有个迷之错误是错的。

如果是没有01(如8,7)就在最高位前补个0.

代码

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;
int s[100];
long long quick(int x){
	if(x==0)return 1;
    long long  s=1,a=2;
    while(x!=1){
        if(x%2==1)s*=a;
        a=a*a;
        x/=2;
    }
    return a*s;
    }
int main(){
	int i,j,k,n,T,flag;
	long long m;
	scanf("%d",&T);k=T;
	while(T--){
		scanf("%d",&n);m=n;
		int l=-1,num=0;		
		long long sum=0;
		while(1){
			if(n%2==0){
			s[++l]=0;
			if(s[l-1]==1)
			break;
				}
			else{
			s[++l]=1;
			sum+=quick(l);
			num++;
			}
			n/=2;
		}
		m=m+quick(l)-quick(l-1);
		long long cha=(sum-quick(l-1))-quick(num-1)+1;
		m-=cha;
		printf("Case :%d %lld\n",k-T,m);
		}
return 0;
}

made by 罗旅洲
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值