位运算 & 打表找规律 J. Even Numbers

https://codeforces.com/gym/101972/problem/J

J. Even Numbers
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Yousef loves playing with functions in his free time. Today, he invents the following function:

Yousef will give you a list of queries, and you need to find the answers for them. For each query, you are given an integer n, and your task is to count the number of integers m in which (0 ≤ m ≤ n) and calc(n,  m) is an even number. Can you?

Input
The first line contains an integer T (1 ≤ T ≤ 105) specifying the number of test cases.

Each test case consists of a single line containing an integer n (0 ≤ n ≤ 1018), as described in the problem statement above.

Output
For each test case, print a single line containing the number of integers m in which (0 ≤ m ≤ n) and calc(n,  m) is an even number.

Example
inputCopy
2
1
2
outputCopy
0
1

打表

#include <algorithm>
#include <cstdio>
#include <iostream>
 
using namespace std;
 
int a[100][100];
 
int main() {
    int n = 32;
    for (int i = 0; i < n; i++) a[0][i] = 1;
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (j > i) a[i][j] = 0;
            if (i == j) a[i][j] = 1;
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (j < i) a[i][j] = (a[i - 1][j - 1] + a[i - 1][j]) % 2;
        }
    }
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++) {
            if (a[i][j] == 1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }

    }

在这里插入图片描述
在这里插入图片描述
n到10的18次方,这么大的数据范围,最多也就是log(n)的算法,或者说是有规律。通过打表发现,对应的2的幂次恰好是 i 的二进制表示中 1 的个数( i 代表第 i 行)

代码

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		long long n, tn, tmp = 0;
		cin>>n;
		tn = n;
		while(tn){
			tn -= tn & (-tn);
			tmp++;
		}
		cout<<n + 1 - (1ll << tmp)<<endl;
		
	}
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值