zoukankan      html  css  js  c++  java
  • [leetcode]题型整理之用bit统计个数

    137. Single Number II

    Given an array of integers, every element appears three times except for one. Find that single one.

    Note:
    Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

    记录32个bit每个bit出现的次数不能被3整除的几位加起来。
     
    201. Bitwise AND of Numbers Range

    Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

    For example, given the range [5, 7], you should return 4.

    Credits:
    Special thanks to @amrsaqr for adding this problem and creating all test cases.

    public class Solution {
        public int rangeBitwiseAnd(int m, int n) {
            int x = 0x40000000;
            //find the first binary from where m is different from n
            int i = 1;
            for(i = 1; i < 32; i++){
                int a = m & x;
                int b = n & x;
                if(a != b){
                    break;
                }
                x = x >> 1;
            }
            i--;
            //i is the last binary where m is the same as n
            int y = 0x80000000;
            y = y >> i;
            int result = m & y;
            return result;
        }
    }

    九章的代码更短

    268. Missing Number

    Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

    For example,
    Given nums = [0, 1, 3] return 2.

    Note:
    Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

    public class Solution {
        public int missingNumber(int[] nums) {
            int n = nums.length;
            int sum = nums[0];
            for (int i = 1; i < n; i++) {
                sum = sum ^ nums[i];
            }
            int sum2 = 0;
            for (int i = 1; i <= n; i++) {
                sum = sum ^ i;
            }
            return sum2 ^ sum;
        }
    }

     how to decide if a number is power of 2?

    (num&-num) == num

  • 相关阅读:
    C#自定义控件之数字文本框
    C# 校验字符串是否为IP格式
    C# winform 解决加载闪烁,背景透明等问题
    SQL Server 数据类型
    C#自定义控件之下拉列表框
    C#将 byte[ ] 转换为对应的struct
    AFNetworking图片上传
    xfs删除oracle数据文件恢复
    揭秘String类型背后的故事——带你领略汇编语言魅力
    [批处理]截取for命令里面的变量%%i
  • 原文地址:https://www.cnblogs.com/Gryffin/p/6237074.html
Copyright © 2011-2022 走看看