Bit computing topics

LeetCode 231: Given an integer, write a function to determine whether it is a power of two.

Example 1:

Input: 1
Output: true
explanation: 20 = 1

Example 2:

Input: 16
Output: true
explanation: 24 = 16

Example 3:

Input: 218
Output: false

method one:

  Ideas: This question determines the number of the digital binary 1 if non-negative, which is only one digit 1 will certainly be a power of 2, or not a power of 2, so the judge can take a bit compare, but this more slowly, so you can take other measures, namely n & (n-1) will be able to eliminate the right of the first occurrence of 1;

  We can understand, regardless of the last n for a location, such as .... ... 1000 (N number) behind assumed there are N 0 1, for the purposes of a digital subtraction becomes. ... 01111 .... (N number) because all of the back borrow 0 becomes 1, then the two numbers after the last phase will be a 1 (including 1) all become 0. so after we eliminate a 1 if there is a judgment after a certain number then this is not 0, it is only necessary with operation is 0 can be.

1 class Solution 
2 {
3 public:
4     bool isPowerOfTwo(int n) 
5     {
6         if(n<=0) return false;
7         return (n&(n-1))==0;
8     }
9 };

 Method Two:

  Ideas: the largest integer integer powers of 2 is 2 ^ 30; the number of all power modulo 2 are zero; it is not a power of 2 non-zero. This is a tricky way.

1 class Solution 
2 {
3 public:
4     bool isPowerOfTwo(int n) 
5     {
6         return n > 0 && (1<<30)%n == 0;
7     }
8 };

Method three:

  Thinking: x is an integer from computer stored original code; is the complement of the -X-stored (inverted original code plus one); it can be used to experiment 5, -5 & made 5, and then find the relationship;

    Therefore, the calculation can be concluded that the binary x & -x equal to x 1 represents the rightmost inside; because there will only be a power of 2 in a 1, so there is, x & -x == x;

    If x is a number in a plurality, it is x & -x <x.

  Computer representation complement negative numbers, mainly because the computer will adder, not subtraction, so this represents a subtraction function is used to achieve an adder.

1 class Solution 
2 {
3 public:
4     bool isPowerOfTwo(int n)
5     {
6         return n > 0 && (n & -n) == n;
7     }
8 };

LeetCode 762:

  Given two integers L and R, to find the closed interval [L, R & lt] within the range, counting the number of bits set to the integer prime number.

  (Note that the calculation set representing a binary representation of the number 1. For example, the binary representation of 21 is 3 10101 calculation is set. Further, the 1 is not a prime number.)

Example 1:

Input: L = 6, R = 10
Output: 4
explains:
6 -> 110 (2 calculated is set, 2 is a prime number)
7 -> 111 (3 calculated is set, 3 is a prime number)
9 -> 1001 (2 computing a set, a prime number is 2)
10-> 1010 (2 calculated is set, a prime number is 2)

Example 2:

Input: L = 10, R = 15
Output: 5
Explanation:
10 -> 1010 (2 calculated is set, 2 is a prime number)
11--> 1011 (3 calculated is set, 3 is a prime number)
12--> 1100 (2 computing a set, 2 is a prime number)
13--> 1101 (3 calculated is set, 3 is a prime number)
14--> 1110 (3 calculated is set, 3 is a prime number)
15--> 1111 (4 calculated is set, 4 is not a prime number)

note:

L, R is L <= R and is an integer in [1, 10 ^ 6].
R - the maximum value of L is 10000.

Ideas:

  10 ^ 6 maximum data section, is less than 2 ^ 20, the first prime number represented less than 20; and calculating the number of data 1, which is not a prime number is determined to.

 1 class Solution
 2 {
 3 public:
 4     int countPrimeSetBits(int L, int R)
 5     {
 6         unordered_set<int> primes({2, 3, 5, 7, 11, 13, 17, 19});
 7         int res;
 8         for(int i = L; i <= R; i++)
 9         {
10             int= s 0 ;
 . 11              for ( int K = I; K; = K >> . 1 ) = K s + & . 1 ;
 12 is              IF (primes.count (s)) RES ++ ; // COUNT () s are used to find primes number.
13 is          }
 14          return RES;
 15      }
 16 };

LeetCode 136: Digital I appear only once

  Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements. Description: Your algorithm should have linear time complexity. You can not use the extra space to achieve it?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

  思路: a ^ a = 0;

     0 ^ a = a;

 1 class Solution 
 2 {
 3 public:
 4     int singleNumber(vector<int>& nums)
 5     {
 6         int res = 0;
 7         for(auto x : nums) res ^= x;
 8         return res;
 9     }
10 };

LeetCode 476:

  Given a positive integer, output its complement. Complement is a negation of the binary number.

note:

  To ensure that a given integer in the range of 32-bit signed integer. You can assume that the binary number without the leading zero.

Example 1:

Input: 5
Output: 2
Explanation: 5 is represented by binary 101 (no leading zero bits), which is the complement of 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: 1 is represented by a binary 1 (no leading zero bits), which complement is 0. So you need to output 0.

method one: 

  Suppose a is 1110 0101, b is 1111 1111, a ^ b = 0001 1010 is a negated. That is the same number of bits and num, and the whole number of 1 tmp and num Or is also desired.

 1 class Solution 
 2 {
 3 public:
 4     int findComplement(int num) 
 5     {
 6         int tmp = 1;
 7         while (tmp < num)
 8         {
 9             tmp <<= 1;
10             tmp += 1;
11         }
12         return (tmp^num);
13     }
14 };

Method Two:

  Sequentially shifting negated.

. 1  class Solution 
 2  {
 . 3  public :
 . 4      int findComplement ( int NUM) 
 . 5      {
 . 6          int RES = 0 , T = 0 ;
 . 7          the while (NUM)
 . 8          {
 . 9              RES + = (& NUM! . 1 ) << T; // this must be taken! and not take - because! Operation, that is, 0, 1 is 0; and - computation, all bits are inverted.
10              NUM = >> . 1 ;
 . 11              T ++ ;
 12 is          }
 13 is          return RES;
14     }
15 };

LeetCode 137: appears only once in the digital II

  Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears three times. To find out that only appears once in the elements.

Description: Your algorithm should have linear time complexity. You can not use the extra space to achieve it?

Example 1:

Input: [qCW]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

A best practice method :()

Ideas :( idea of ​​the state machine) (not quite understand)

  Do not take into account the position of the binary adder: 136 questions, we used the XOR. In practice, the meaning of the XOR operation does not take into account bit binary adder,

    That is: 0 = 0 ^ 0 ^ 0 + 0 = 0 0 = 0 + 0 = 0,

      0 ^ 1 = 0 + 1 = 1  0 ^ 1 = 0 + 1 = 1,

      1 ^ 0 = 1 + 0 = 1 1 ^ 0 = 1 + 0 = 1,

      1 = 1 ^ + 1 ^ 1 = 0 1 1 = 1 + 1 = 0 (no carry).

  Without considering the carry bit of the adder ternary: # by defining a certain operation, such that 1 = 0 # 1,1 # 2,2 # 1 = 1 = 0. In this operation rules, appeared three times in all digital binary bits are all offset to zero, leaving only appear once the corresponding digital binary bits to 1.

    Therefore, under this rule the entire operation of the digital arr traversal plus and, once left to the digital result was only occur.

 

 1 class Solution 
 2 {
 3 public:
 4     int singleNumber(vector<int>& nums)
 5     {
 6         int ones = 0, twos = 0;
 7         for(auto x : nums)
 8         {
 9             ones = (ones ^ x) & ~twos;
10             twos = (twos ^ x) & ~ones;
11         }
12         return ones;
13     }
14 };

 方法二:(一般做法)

   分别对所有数据的每一位进行对3取余操作。

 1 class Solution 
 2 {
 3 public:
 4     int singleNumber(vector<int>& nums)
 5     {
 6         int ans = 0;
 7         for(int bit = 0; bit < 32; bit++)
 8         {
 9             int counter = 0;
10             for(int i = 0; i < nums.size(); i++)
11             {
12                 counter += (nums[i] >> bit) & 1;
13             }
14             
15             ans += (counter % 3) << bit;
16         }
17         return ans;
18     }
19 };

 LeetCode 260:只出现一次的数据III

  给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。

示例 :

输入: [1,2,1,3,2,5]
输出: [3,5]
注意:结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?

   思路:

    第一步:
      把所有的元素进行异或操作,最终得到一个异或值。因为是不同的两个数字,所以这个值必定不为0;

    第二步:
      取异或值最后一个二进制位为1的数字作为mask,如果是1则表示两个数字在这一位上不同。

    第三步:
      分组,就可以找出两个数。

 1 class Solution 
 2 {
 3 public:
 4     vector<int> singleNumber(vector<int>& nums) 
 5     {
 6         int s = 0;
 7         for(auto x : nums) s ^= x;
 8         
 9         int k = 0;
10         while(!(s >> k & 1)) k++;
11         
12         int s2 = 0;
13         for(int x : nums)
14         {
15             if(x >> k & 1)
16                 s2 ^= x;
17         }
18         /*
19             s = a ^ b;
20             s2 = a;
21             s ^ s2 = a ^ b ^ a = b;
22         */
23         
24         return {s2, s2 ^ s}; // vector<int> ({s2, s2 ^ s});
25     }
26 };

 LeetCode 371:不使用运算符 + 和 - ​​​​​​​,计算两整数 ​​​​​​​a 、b ​​​​​​​之和。

示例 1:

输入: a = 1, b = 2
输出: 3

示例 2:

输入: a = -2, b = 3
输出: 1

 思路:a ^ b 是不进位加法;a & b 只有在相对应的位都为1的时候才为1,所以a & b 表示有进位的位;所以,结果等于 a ^ b + (a & b) << 1;

 1 class Solution
 2 {
 3 public:
 4     int getSum(int a, int b)
 5     {
 6         if(!b) return a;
 7         int sum = a ^ b, carry = (unsigned int)(a & b) << 1; // 这里将a&b强转unsigned int,是因为有的不支持负数左移
 8         return getSum(sum, carry);
 9     }
10 };

 LeetCode 201:给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。2147483647 这个数是int的最大值。

示例 1: 

输入: [5,7]
输出: 4

示例 2:

输入: [0,1]
输出: 0

思路:

  判断m、n是否相等,如果不相等,m+1会使m的二进制数末位进位,有进位说明m的末位肯定有0的情况,0与任何数相与皆得0,所以结果的末位肯定是0。

  同理,不断右移1位进行比较,直到最终 m=n 时,说明找到了[m,n]这个范围内高位没有变化的数,左移相同位数得到的结果就是所求的值。

法一:

class Solution
{
public:
    int rangeBitwiseAnd(int m, int n)
    {
        int count = 0; // 统计移位次数
        while (m != n)
        {
            m >>= 1;
            n >>= 1;
            count++;
        }
        n <<= count;
        return n;
    }
};

法二:

 1 class Solution 
 2 {
 3 public:
 4     int rangeBitwiseAnd(int m, int n) 
 5     {
 6         while(n>m) 
 7             n = n&(n-1);
 8         return n;
 9     }
10 };

 

Guess you like

Origin www.cnblogs.com/WPF-342201/p/11426944.html