寻找10001

所谓SQ问题是指,Second Q(第17[10001]个字母),给定一个数字,请找到二进制中倒数第二个10001.
输入描述
第一行:n,表示有n组样例,接下来n行,每行一个数字a[i]。
n<2*10^5
a[i]<2^64
输出描述
如果找不到输出-1,否则输出倒数第二个10001的最后一个1出现在第几位。
样例枚举了很多情况,请参照样例。
Input
4

273

561

16

1122

Output
5

6

-1

7
数据范围最大2^64-1,所以只能用unsigned long long,读入用scanf("%llu")。

#include<iostream>
#include<stack>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	int z;
	scanf("%d", &z);
	while (z--)
	{
		unsigned long long a;
		scanf("%llu", &a);
		stack<int>s;
		long long c[1000];
		int k = 0;
		while (a > 0) {
			c[k] = a % 2;
			k++;
			a = a / 2;
		}
		for (int i = k - 1; i >= 0; i--)
		{
			s.push(c[i]);
		}
		char b[5]={'0'};
		int i = 0;
		int cnt = 0;
		int ans = 0;
		int m = 1;
		while (!s.empty())
		{
			if (i < 5)
			{
				b[i] = s.top() + '0';
				s.pop();
				ans++;
				i++;
			}
			else
			{
				for (int j = 1; j < 5; j++)
				{
					b[j - 1] = b[j];
				}
				b[4] = s.top() + '0';
				s.pop();
				ans++;
			}
			if (strcmp(b, "10001") == 0 && cnt == 0)
			{
				cnt = 1;
				for (int j = 0; j < 5; j++)
				{
					b[j] = '0';
				}
				s.push(1);
				ans--;
				i = 0;
			}
			if (strcmp(b, "10001") == 0 && cnt == 1)
			{
				printf("%d\n", ans - 4);
				m = 0;
				break;
			}
		}
		if (m == 1)
			printf("-1\n");
		while (!s.empty())
		{
			s.pop();
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值