Nearest numbers with the same number of set bits

Given a positive integer ‘n’, your task is to find the next smallest integer and the previous largest integer having the exact number of ‘1’ bits set in their binary representation as ‘n’.

Example:
‘n = 6’
The binary representation of 6 = ‘0110’, which has two ‘1’ bits set.
Next smallest integer = 9 = ‘1001’, the smallest integer greater than 6 having two ‘1’ bits set.
Previous largest integer = 5 = ‘0101’, largest integer smaller than 6 having two ‘1’ bits set.
Therefore, the answer is {9, 5}.
Note:
1. ‘n’ is a positive integer greater than one.
2. For any given integer ‘n’, there is always a positive integer smaller than ‘n’ having the exact number of ‘1’ bits set.
3. Don’t print anything. Just implement the function and return the answer.
4. ‘n’ can have a max of ‘30’ bits.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The next line of each test case consists of a single line containing the integer ‘n’.
Output format:
For each test case, print the next smallest integer, the previous largest integer to ‘n’ with the exact number of ‘1’ bits set.

The output of each test case should be printed in a new line.
Constraints:
1 <= T <= 10000
‘n’ can have ‘30’ bits at max

Where ‘T’ is the number of test cases, and ‘n’ is the given integer.

Time limit: 1 second
CodingNinjas
author
2y

Approach :

When we observe the binary sequence from 0 to 2n – 1 (n is no. of bits), right most bits (least significant) vary rapidly than left most bits. The idea is to find right most string of 1’s in...read more

CodingNinjas
author
2y
Brute force

The brute force approach would be to count the number of ‘1’ bits in ‘n’ and then increment (or decrement) from ‘n’ until we find an integer with an exact count of ‘1’ bits.

  • Count the numbe...read more
CodingNinjas
author
2y
Bit-manipulation

Observation: Consider the location of two bits for a number ‘n’ as ‘i’ and ‘j’. To maintain the same number of 1 bit in ‘n’, if we flip the ‘i-th’ bit from 1 to 0, we must convert the...read more

CodingNinjas
author
2y
Arithmetic approach

This approach is similar to the bit-manipulation approach, but we want to use as little bit-manipulation as possible.

1. To find the next smallest number:

Let 'next' be the next small...read more

Add answer anonymously...
Nagarro Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter