TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
next_higher_number_with_same_number_of_set_bits.cpp File Reference

[Next higher number with same number of set bits] (https://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/) implementation More...

#include <cassert>
#include <cstdint>
#include <iostream>
Include dependency graph for next_higher_number_with_same_number_of_set_bits.cpp:

Go to the source code of this file.

Namespaces

namespace  bit_manipulation
 for assert
 

Functions

uint64_t bit_manipulation::next_higher_number (uint64_t x)
 The main function implements checking the next number.
 
static void test ()
 Self-test implementations.
 
int main ()
 Main function.
 

Detailed Description

[Next higher number with same number of set bits] (https://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/) implementation

Given a number x, find next number with same number of 1 bits in it’s binary representation. For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).

A binary number consists of two digits. They are 0 & 1. Digit 1 is known as set bit in computer terms.

Author
Kunal Nayak

Definition in file next_higher_number_with_same_number_of_set_bits.cpp.

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 98 of file next_higher_number_with_same_number_of_set_bits.cpp.

98 {
99 test(); // run self-test implementations
100 return 0;
101}
static void test()
Self-test implementations.

◆ test()

static void test ( )
static

Self-test implementations.

Returns
void

Definition at line 74 of file next_higher_number_with_same_number_of_set_bits.cpp.

74 {
75 // x = 4 return 8
77 // x = 6 return 9
79 // x = 13 return 14
81 // x = 64 return 128
82 assert(bit_manipulation::next_higher_number(64) == 128);
83 // x = 15 return 23
85 // x= 32 return 64
87 // x = 97 return 98
89 // x = 1024 return 2048
90 assert(bit_manipulation::next_higher_number(1024) == 2048);
91
92 std::cout << "All test cases have successfully passed!" << std::endl;
93}
uint64_t next_higher_number(uint64_t x)
The main function implements checking the next number.