• 算法14-----位运算操作(1)


    1、应用技巧1:与&【消除x(二进制)最后一位1】

    def checkPowerof2(x):
        return x>0 and x&(x-1)==0

    应用三:判断n是否为4的幂:

    def isFour(n):
        m=1
        while m<n:
            m=m<<2
        return m==n

    2、应用技巧2:子集

    // Non Recursion
    class Solution {
        /**
         * @param S: A set of numbers.
         * @return: A list of lists. All valid subsets.
         */
        public List<ArrayList<Integer>> subsets(int[] nums) {
            List<ArrayList<Integer>> result = new ArrayList<List<Integer>>();
            int n = nums.length;
            Arrays.sort(nums);
            
            // 1 << n is 2^n
            // each subset equals to an binary integer between 0 .. 2^n - 1
            // 0 -> 000 -> []
            // 1 -> 001 -> [1]
            // 2 -> 010 -> [2]
            // ..
            // 7 -> 111 -> [1,2,3]
            for (int i = 0; i < (1 << n); i++) {
                List<Integer> subset = new ArrayList<Integer>();
                for (int j = 0; j < n; j++) {
                    // check whether the jth digit in i's binary representation is 1
                    if ((i & (1 << j)) != 0) {
                        subset.add(nums[j]);
                    }
                }
                result.add(subset);
            }
            
            return result;
        }
    }

    3、应用技巧3:异或

     

    java代码:

    public class Solution {
        public int singleNumber(int[] nums) {
            int ones = 0, twos = 0;
            for(int i = 0; i < nums.length; i++){
                ones = (ones ^ nums[i]) & ~twos;
                twos = (twos ^ nums[i]) & ~ones;
            }
            return ones;
        }
    }

    public class Solution {
        public int[] singleNumber(int[] nums) {
            //用于记录,区分“两个”数组
            int diff = 0;
            for(int i = 0; i < nums.length; i ++) {
                diff ^= nums[i];
            }
            //取最后一位1
            //先介绍一下原码,反码和补码
            //原码,就是其二进制表示(注意,有一位符号位)
            //反码,正数的反码就是原码,负数的反码是符号位不变,其余位取反
            //补码,正数的补码就是原码,负数的补码是反码+1
            //在机器中都是采用补码形式存
            //diff & (-diff)就是取diff的最后一位1的位置
            diff &= -diff;
            
            int[] rets = {0, 0}; 
            for(int i = 0; i < nums.length; i ++) {
                //分属两个“不同”的数组
                if ((nums[i] & diff) == 0) {
                    rets[0] ^= nums[i];
                }
                else {
                    rets[1] ^= nums[i];
                }
            }
            return rets;
        }
    }
  • 相关阅读:
    通过按键实现LED灯的亮灭(含两种情况)
    让大疆去做测绘---航线规划软件APP
    GPIOLED配置、key、中断NVIC配置
    使用指针的指针对字符串排序
    使用指针输出数组元素
    使用指针创建数组
    求输出此日期是该年的第几天
    婚礼上的谎言/百元买白鸡
    使用指针的指针对字符串排序
    实例168 使用指针输出数组元素
  • 原文地址:https://www.cnblogs.com/Lee-yl/p/9006028.html
Copyright © 2020-2023  润新知