2021阿里实习生笔试(2021-3-15)

第一题

题目大概就是给你三个数a,b,c 然后对a 和 b二进制位操作。一次操作只能是对其中任意一个数的二进制位进行取反。就是问你经过最少的操作使得a|b=c.

代码实现

package com.fwh;

import java.util.Scanner;

/**
 * @ClassName Main
 * @Description :TODO
 * @Author Josvin
 * @Date 2021/03/15/19:05
 */
public class Main {
     
    public static void main(String[] args) {
     
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();// n = 2
        while (n-- > 0) {
     
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            int c = scanner.nextInt();
            // 计算出 a|b 后,结果于c不相同的地方就是需要进行操作的。(有可能需要操作的位对两个数都需要操作)
            int d = a | b;
            // 将a&b中为1的bit位并且与   a&b&c  中不同的bit位置为1  
            int t = (a & b) ^ (a & b & c);// 0010 0110   0010  0101
            int cc = t & c;
            // 这里就是找出那些bit位是需要改两次的
            int count1 = 0;
            while (t != 0) {
     
                if ((t & 1) == 1) {
     
                    count1++;
                }
                t = t >>> 1;
            }
            int ans = d ^ c;
            int count = 0;
            while (ans != 0) {
     
                if ((ans & 1) == 1) {
     
                    count++;
                }
                ans = ans >>> 1;
            }

            System.out.println(count1 + count);
        }
    }
}

第二题蜡烛

由于第一题浪费时间太多,第二题没看清叙述。直接返回了一个n/2不对!!!

你可能感兴趣的:(每日一题,位运算,实习笔试)