enh(CPlusPlus): add missing space to power-of-two maths (#667)
Co-authored-by: Rahul Rajeev Pillai <66192267+Ashborn-SM@users.noreply.github.com> Co-authored-by: datshan-trivedi-10 <dbtrivedi03@gmail.com>pull/540/head^2
parent
110518e7c6
commit
f97cb54a2e
|
@ -1,27 +1,37 @@
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
//function starts
|
// function starts
|
||||||
bool isPowerOfTwo(const n)
|
bool isPowerOfTwo(const int n)
|
||||||
{
|
{
|
||||||
//declare a variable to know if n is a power of 2 or not
|
// declare a variable to know if n is a power of 2 or not
|
||||||
long i = 1;
|
long i = 1;
|
||||||
//at every iteration it will calcalute power of 2 starting from 1
|
// at every iteration it will calcalute power of 2 starting from 1
|
||||||
while (i < n)
|
while (i < n)
|
||||||
{
|
{
|
||||||
i = i * 2;
|
i = i * 2;
|
||||||
}
|
}
|
||||||
//if n is the power of 2, i and n value will be same
|
// if n is the power of 2, i and n value will be same
|
||||||
//if they are same, it will return true, else it will return false
|
// if they are same, it will return true, else it will return false
|
||||||
return i == n;
|
return i == n;
|
||||||
}
|
}
|
||||||
|
|
||||||
//main starts
|
// Binary Method to check number is in power of two or not.
|
||||||
|
// Time Complexity of this method is O(1)
|
||||||
|
bool ispoweroftwo(const int n)
|
||||||
|
{
|
||||||
|
// if number is in power of two it will give 0, otherwise it will not zero.
|
||||||
|
return n != 0 && (n & (n - 1)) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// main starts
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
int n;
|
int n;
|
||||||
cin >> n;
|
cin >> n;
|
||||||
cout << isPowerOfTwo(n);
|
cout << isPowerOfTwo(n) << endl;
|
||||||
|
// Check using Binary Method
|
||||||
|
cout << ispoweroftwo(n) << endl;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -29,13 +39,15 @@ int main()
|
||||||
Example 1:
|
Example 1:
|
||||||
|
|
||||||
Input: n = 1
|
Input: n = 1
|
||||||
Output:1 (true)
|
Output:1 (true)
|
||||||
Explanation: 20 = 1
|
Explanation: 2^0 = 1
|
||||||
|
|
||||||
Example 2:
|
Example 2:
|
||||||
|
|
||||||
Input: n = 16
|
Input: n = 16
|
||||||
Output:1 (true)
|
Output:1 (true)
|
||||||
Explanation: 24 = 16
|
Explanation: 2^4 = 16
|
||||||
|
|
||||||
Example 3:
|
Example 3:
|
||||||
|
|
||||||
Input: n = 3
|
Input: n = 3
|
||||||
|
|
Loading…
Reference in New Issue