题解:2024牛客暑期多校第2场——E [GCD VS XOR]

GCD VS XOR

https://ac.nowcoder.com/acm/contest/81597/E

英文题干

Ben has a positive integer . He wants you to find another positive integer , which is strictly less than , so that the equation holds. Can you help him?

where ⊕ is bitwise XOR operation.

Input:

The first line contains a single integer — the number of test cases. The only line of each test case contains a single integer .

Output:

For each testcase, output a single positive integer , if you find a feasible answer, or −1 otherwise.

中文题干

Ben有一个正整数。他希望你找到另一个严格小于的正整数,使得方程成立。你能帮助他吗?

其中⊕表示按位异或操作。

思路

  1. 首先,若x为奇数:

    先介绍【⊕配对性定理】:若a为任意非负偶数,则必有 a⊕1=(a+1) 。利用这个定理,又由⊕的可交换性大于2且相邻的两个数必互质,故当x为奇数时,x-1即为答案。

  2. 其次,若x为偶数。

    [1].若x是2的整数幂, y不存在。

    [2].否则,只需要寻找x最多能被2的多少次方整除(可以利用 x&-x 求得),用x减去这个数即可。

  3. 最后,注意x=1需要特判一下。

(P.S:本题可以通过找规律直接获得结论,严谨证明见这篇文章

AC代码

时间复杂度:O()

#include <iostream>
#define ll long long
using namespace std;
ll k, n;

void solve() {
    cin >> n;
    if (n == 1)
    {
        cout << -1 << endl;
        return;
    }

    if (n % 2 == 1)
    {
        cout << n - 1 << endl;
        return;
    }
    ll d = n & -n;
    if (d == n)
    {
        cout << -1 << endl;
    }
    else {
        cout << n - d << endl;
    }
}

signed main()
{
    cin >> k;
    while (k--) {
        solve();
    }

    return 0;
}
// Inspired by LXY & ZRJ
全部评论
讲的很清楚
点赞 回复 分享
发布于 2024-07-20 11:44 上海

相关推荐

我看到好多人都在说0offer好焦虑,结果一看是投了百度快手字节啥的。好像大家都是只想通过校招进大厂,对小公司是不考虑的吗😂可是能进大厂的难道不是只有少部分人吗,真心发问
梦想是成为七海千秋:沉默的大多数吧,喜欢晒的都是能引起共鸣的大厂,找小厂的人,别人也不认识你这个小厂,就自己偷偷找了实际上大多数人哪有什么机会能找到大厂
点赞 评论 收藏
分享
05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务