In c++ i want to make a program in which, output is the difference between N(input) and the next highest number in power of 2 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

In c++ i want to make a program in which, output is the difference between N(input) and the next highest number in power of 2

for example if an input 5 is given then, output =8-5=3 if input 19 is given then, output=32-19=13 please help me with the code i should use

14th Oct 2018, 2:55 PM
Chetan Satpute
Chetan Satpute - avatar
4 Answers
14th Oct 2018, 3:51 PM
Aleksander Szczepura
Aleksander Szczepura - avatar
+ 4
// n is input int x=n, y=1; while(x>>=1) y<<=1; return y-n;
14th Oct 2018, 4:09 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 1
// If you enter a number which is already power of 2 then I go for next power of two. #include <iostream> #include <cmath> using namespace std; int getCount(int n){ int i = 0; while(n){ n>>=1; i++; } return i; } int main() { int n; std::cin >> n; int ans = pow(2,getCount(n)); std::cout << ans << "-" << n << "=" << ans-n; return 0; }
14th Oct 2018, 3:40 PM
Tanay
Tanay - avatar
+ 1
thank you sir
14th Oct 2018, 3:44 PM
Chetan Satpute
Chetan Satpute - avatar