Check if the 20th bit of a 32 bit integer is on or off?

AND it with x00001000 and check if its equal to x00001000

if((num & x00001000)==x00001000)

Note that the digits represented here are in hex.

`
     0      0      0      0      1      0      0      0
                                 ^                   
                                 |

 x0000   0000   0000   0000   0001   0000   0000   0000 = 32 bits

  ^                              ^                    ^
  |                              |                    |

  0th bit                        20th bit             32nd bit
`

Count bits set in an integer

Question: Write a function that determines the number of bits set to 1 in the binary representation of an integer. Method 1 - Simple method (Right shift integer until it becomes 0) Going by the brute force approach, it would be easy to come up with the following solution. If the least significant bit of a number is 1, it will return a result of 1 when we AND it with 1. [Read More]

Find all sets of consecutive integers that add up to 1000.

There are total 8 such series: 1. Sum of 2000 numbers starting from -999 i.e. summation of numbers from -999 to 1000. (-999) + (-998) + (-997) + ….. + (-1) + 0 + 1 + 2 + ….. + 997 + 998 + 999 + 1000 = 1000 2. Sum of 400 numbers starting from -197 i.e. summation of numbers from -197 to 202. (-197) + (-196) + (-195) + …. [Read More]

Code to check if an integer is a power of 2 or not in a single line

Problem Check if integer is power of 2 or not FOLLOW UP - Preferable solution to get it in 1 line. Solution Method1 All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. We have discussed how to count number of bits set here. Method 2 Note that the bit pattern of a power of two is of the form 10…0 and that of a number just one less is 011…1. [Read More]