巧用异或运算符(洛谷P1161题题解,Java语言描述)

题目要求

P1161题目链接

在这里插入图片描述
在这里插入图片描述

分析

我们只需要设result=0,然后把所有的数异或一遍。
因为只有一盏灯是开的,也就是说,其他编号出现的次数都是成对的,异或结果都是0,剩下的那一个与0异或得它本身。
因此最后result就是结果。

AC代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt(), t, result=0;
        double a;
        for (int i = 0; i < num; i++) {
            a = scanner.nextDouble();
            t = scanner.nextInt();
            for (int j = 1; j <= t; j++) {
                int x = (int)Math.floor(a*j);
                result ^= x;
            }
        }
        System.out.println(result);
        scanner.close();
    }
}
发布了351 篇原创文章 · 获赞 610 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/103700293
今日推荐