Program to find whether a given number is power of 2
Last Updated :
16 Jul, 2024
Given a positive integer n, write a function to find if it is a power of 2 or not
Examples:
Input : n = 4
Output : Yes
Explanation: 22 = 4
Input : n = 42
Output : No
Explanation: 42 is not a power of 2
Input : n = 1
Output : Yes
Explanation: 20 = 1
Finding whether a given number is a power of 2 using Log operator:
A simple method for this is to simply take the log of the number on base 2 and if you get an integer then the number is the power of 2
Below is the implementation of the above approach:
C++
// C++ Program to find whether a
// no is a power of two
#include <bits/stdc++.h>
using namespace std;
// Function to check if x is power of 2
bool isPowerOfTwo(int n)
{
if (n == 0)
return false;
return (ceil(log2(n)) == floor(log2(n)));
}
// Driver code
int main()
{
// Function call
isPowerOfTwo(31) ? cout << "Yes" << endl
: cout << "No" << endl;
isPowerOfTwo(64) ? cout << "Yes" << endl
: cout << "No" << endl;
return 0;
}
// This code is contributed by Surendra_Gangwar
C
// C Program to find whether a
// no is power of two
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
if (n == 0)
return false;
return (ceil(log2(n)) == floor(log2(n)));
}
// Driver code
int main()
{
// Function call
isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n");
isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n");
return 0;
}
// This code is contributed by bibhudhendra
Java
// Java Program to find whether a
// no is power of two
import java.lang.Math;
class GFG {
/* Function to check if x is power of 2*/
static boolean isPowerOfTwo(int n)
{
if (n == 0)
return false;
return (int)(Math.ceil((Math.log(n) / Math.log(2))))
== (int)(Math.floor(
((Math.log(n) / Math.log(2)))));
}
// Driver Code
public static void main(String[] args)
{
// Function call
if (isPowerOfTwo(31))
System.out.println("Yes");
else
System.out.println("No");
if (isPowerOfTwo(64))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by mits
Python
# Python3 Program to find
# whether a no is
# power of two
import math
# Function to check
# Log base 2
def Log2(x):
if x == 0:
return false
return (math.log10(x) /
math.log10(2))
# Function to check
# if x is power of 2
def isPowerOfTwo(n):
return (math.ceil(Log2(n)) ==
math.floor(Log2(n)))
# Driver Code
if __name__ == "__main__":
# Function call
if(isPowerOfTwo(31)):
print("Yes")
else:
print("No")
if(isPowerOfTwo(64)):
print("Yes")
else:
print("No")
# This code is contributed
# by mits
C#
// C# Program to find whether
// a no is power of two
using System;
class GFG {
/* Function to check if
x is power of 2*/
static bool isPowerOfTwo(int n)
{
if (n == 0)
return false;
return (int)(Math.Ceiling(
(Math.Log(n) / Math.Log(2))))
== (int)(Math.Floor(
((Math.Log(n) / Math.Log(2)))));
}
// Driver Code
public static void Main()
{
// Function call
if (isPowerOfTwo(31))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
if (isPowerOfTwo(64))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
JavaScript
// javascript Program to find whether a
// no is power of two
function isPowerOfTwo(n)
{
return n > 0 && Math.log2(n) % 1 === 0;
}
// Driver Code
if (isPowerOfTwo(31))
console.log("Yes");
else
console.log("No");
if (isPowerOfTwo(64))
console.log("Yes");
else
console.log("No");
PHP
<?php
// PHP Program to find
// whether a no is
// power of two
// Function to check
// Log base 2
function Log2($x)
{
return (log10($x) /
log10(2));
}
// Function to check
// if x is power of 2
function isPowerOfTwo($n)
{
return (ceil(Log2($n)) ==
floor(Log2($n)));
}
// Driver Code
// Function call
if(isPowerOfTwo(31))
echo "Yes\n";
else
echo "No\n";
if(isPowerOfTwo(64))
echo "Yes\n";
else
echo "No\n";
// This code is contributed
// by Sam007
?>
Time Complexity: O(1)
Auxiliary Space: O(1)
Finding whether a given number is a power of 2 using the modulo & division operator:
Keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
if (n == 0)
return 0;
while (n != 1) {
if (n % 2 != 0)
return 0;
n = n / 2;
}
return 1;
}
// Driver code
int main()
{
// Function call
isPowerOfTwo(31) ? cout << "Yes\n" : cout << "No\n";
isPowerOfTwo(64) ? cout << "Yes\n" : cout << "No\n";
return 0;
}
// This code is contributed by rathbhupendra
C
// C program for the above approach
#include <stdbool.h>
#include <stdio.h>
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
if (n == 0)
return 0;
while (n != 1) {
if (n % 2 != 0)
return 0;
n = n / 2;
}
return 1;
}
// Driver code
int main()
{
// Function call
isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n");
isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n");
return 0;
}
Java
// Java program to find whether
// a no is power of two
import java.io.*;
class GFG {
// Function to check if
// x is power of 2
static boolean isPowerOfTwo(int n)
{
if (n == 0)
return false;
while (n != 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
// Driver code
public static void main(String args[])
{
// Function call
if (isPowerOfTwo(31))
System.out.println("Yes");
else
System.out.println("No");
if (isPowerOfTwo(64))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Nikita tiwari.
Python
# Python program to check if given
# number is power of 2 or not
# Function to check if x is power of 2
def isPowerOfTwo(n):
if (n == 0):
return False
while (n != 1):
if (n % 2 != 0):
return False
n = n // 2
return True
# Driver code
if __name__ == "__main__":
# Function call
if(isPowerOfTwo(31)):
print('Yes')
else:
print('No')
if(isPowerOfTwo(64)):
print('Yes')
else:
print('No')
# This code is contributed by Danish Raza
C#
// C# program to find whether
// a no is power of two
using System;
class GFG {
// Function to check if
// x is power of 2
static bool isPowerOfTwo(int n)
{
if (n == 0)
return false;
while (n != 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
// Driver code
public static void Main()
{
// Function call
Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No");
Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No");
}
}
// This code is contributed by Sam007
JavaScript
/* Function to check if x is power of 2*/
function isPowerOfTwo(n)
{
if (n == 0)
return 0;
while (n != 1)
{
if (n%2 != 0)
return 0;
n = n/2;
}
return 1;
}
isPowerOfTwo(31)? console.log("Yes"): console.log("No");
isPowerOfTwo(64)? console.log("Yes"): console.log("No");
PHP
<?php
// php program for the above approach
// Function to check if
// x is power of 2
function isPowerOfTwo($n)
{
if ($n == 0)
return 0;
while ($n != 1)
{
if ($n % 2 != 0)
return 0;
$n = $n / 2;
}
return 1;
}
// Driver Code
// Function call
if(isPowerOfTwo(31))
echo "Yes\n";
else
echo "No\n";
if(isPowerOfTwo(64))
echo "Yes\n";
else
echo "No\n";
// This code is contributed
// by Sam007
?>
Time Complexity: O(log N)
Auxiliary Space: O(1)
To solve the problem follow the below idea:
All power of two numbers has only a one-bit set. So count the no. of set bits and if you get 1 then the number is a power of 2. Please see Count set bits in an integer for counting set bits.
Below is the implementation of the above approach:
C++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
/* First x in the below expression is for the case when
* x is 0 */
int cnt = 0;
while (n > 0) {
if ((n & 1) == 1) {
cnt++;
}
n = n >> 1; // keep dividing n by 2 using right
// shift operator
}
if (cnt == 1) { // if cnt = 1 only then it is power of 2
return true;
}
return false;
}
// Driver code
int main()
{
// Function call
isPowerOfTwo(31) ? cout << "Yes\n" : cout << "No\n";
isPowerOfTwo(64) ? cout << "Yes\n" : cout << "No\n";
return 0;
}
// This code is contributed by devendra salunke
Java
// Java program of the above approach
import java.io.*;
class GFG {
// Function to check if x is power of 2
static boolean isPowerofTwo(int n)
{
int cnt = 0;
while (n > 0) {
if ((n & 1) == 1) {
cnt++; // if n&1 == 1 keep incrementing cnt
// variable
}
n = n >> 1; // keep dividing n by 2 using right
// shift operator
}
if (cnt == 1) {
// if cnt = 1 only then it is power of 2
return true;
}
return false;
}
// Driver code
public static void main(String[] args)
{
// Function call
if (isPowerofTwo(30) == true)
System.out.println("Yes");
else
System.out.println("No");
if (isPowerofTwo(128) == true)
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by devendra salunke.
Python
# Python3 program to check if given
# number is power of 2 or not
# Function to check if x is power of 2
def isPowerOfTwo(n):
cnt = 0
while n > 0:
if n & 1 == 1:
cnt = cnt + 1
n = n >> 1
if cnt == 1:
return 1
return 0
# Driver code
if __name__ == "__main__":
# Function call
if(isPowerOfTwo(31)):
print('Yes')
else:
print('No')
if(isPowerOfTwo(64)):
print('Yes')
else:
print('No')
# This code is contributed by devendra salunke
C#
// C# program to check for power for 2
using System;
class GFG {
// Method to check if x is power of 2
static bool isPowerOfTwo(int n)
{
int cnt = 0; // initialize count to 0
while (n > 0) {
// run loop till n > 0
if ((n & 1) == 1) {
// if n&1 == 1 keep incrementing cnt
// variable
cnt++;
}
n = n >> 1; // keep dividing n by 2 using right
// shift operator
}
if (cnt
== 1) // if cnt = 1 only then it is power of 2
return true;
return false;
}
// Driver code
public static void Main()
{
// Function call
Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No");
Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No");
}
}
// This code is contributed by devendra salunke
JavaScript
// JavaScript code for the above approach
// Function to check if x is power of 2
function isPowerofTwo(n)
{
let cnt = 0;
while (n > 0) {
if ((n & 1) == 1) {
cnt++; // if n&1 == 1 keep incrementing cnt
// variable
}
n = n >> 1; // keep dividing n by 2 using right
// shift operator
}
if (cnt == 1) {
// if cnt = 1 only then it is power of 2
return true;
}
return false;
}
// Driver code
if (isPowerofTwo(30) == true)
console.log("Yes");
else
console.log("No");
if (isPowerofTwo(128) == true)
console.log("Yes");
else
console.log("No");
Time complexity: O(log N)
Auxiliary Space: O(1)
Finding whether a given number is a power of 2 using the AND(&) operator:
To solve the problem follow the below idea:
If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit becomes unset.
For example for 4 ( 100) and 16(10000), we get the following after subtracting 1
3 –> 011
15 –> 01111
So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on the value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case).
Note: With any method which involves subtraction by 1 (just as below, ‘n-1’), some online platforms may give an error if n is given the minimum value of integer or -2147483648. Subtraction by 1 gives integer overflow error in C++.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int x)
{
if(x<0) return false;
/* First x in the below expression is for the case when
* x is 0 */
return x && (!(x & (x - 1)));
}
// Driver code
int main()
{
// Function call
isPowerOfTwo(31) ? cout << "Yes\n" : cout << "No\n";
isPowerOfTwo(64) ? cout << "Yes\n" : cout << "No\n";
return 0;
}
// This code is contributed by rathbhupendra
C
// C program for the above approach
#include <stdio.h>
#define bool int
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int x)
{
/* First x in the below expression is for the case when
* x is 0 */
return x && (!(x & (x - 1)));
}
// Driver code
int main()
{
// Function call
isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n");
isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n");
return 0;
}
Java
// Java program for the above approach
class Test {
/* Method to check if x is power of 2*/
static boolean isPowerOfTwo(int x)
{
/* First x in the below expression is
for the case when x is 0 */
return x != 0 && ((x & (x - 1)) == 0);
}
// Driver code
public static void main(String[] args)
{
// Function call
System.out.println(isPowerOfTwo(31) ? "Yes" : "No");
System.out.println(isPowerOfTwo(64) ? "Yes" : "No");
}
}
// This program is contributed by Gaurav Miglani
Python
# Python3 program for the above approach
# Function to check if x is power of 2
def isPowerOfTwo(x):
# First x in the below expression
# is for the case when x is 0
return (x and (not(x & (x - 1))))
# Driver code
if __name__ == "__main__":
# Function call
if(isPowerOfTwo(31)):
print('Yes')
else:
print('No')
if(isPowerOfTwo(64)):
print('Yes')
else:
print('No')
# This code is contributed by Danish Raza
C#
// C# program for the above approach
using System;
class GFG {
// Method to check if x is power of 2
static bool isPowerOfTwo(int x)
{
// First x in the below expression
// is for the case when x is 0
return x != 0 && ((x & (x - 1)) == 0);
}
// Driver code
public static void Main()
{
// Function call
Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No");
Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No");
}
}
// This code is contributed by Sam007
JavaScript
// JavaScript program to efficiently
// check for power for 2
/* Method to check if x is power of 2*/
function isPowerOfTwo (x)
{
/* First x in the below expression is
for the case when x is 0 */
return x!=0 && ((x&(x-1)) == 0);
}
// Driver method
console.log(isPowerOfTwo(31) ? "Yes" : "No");
console.log(isPowerOfTwo(64) ? "Yes" : "No");
PHP
<?php
// php program for the above approach
// Function to check if
// x is power of 2
function isPowerOfTwo ($x)
{
// First x in the below expression
// is for the case when x is 0
return $x && (!($x & ($x - 1)));
}
// Driver Code
// Function call
if(isPowerOfTwo(31))
echo "Yes\n" ;
else
echo "No\n";
if(isPowerOfTwo(64))
echo "Yes\n" ;
else
echo "No\n";
// This code is contributed by Sam007
?>
Time Complexity: O(1)
Auxiliary Space: O(1)
Finding whether a given number is a power of 2 using the AND(&) and NOT(~) operator:
To solve the problem follow the below idea:
Another way is to use the logic to find the rightmost bit set of a given number and then check if (n & (~(n-1))) is equal to n or not
Note: With any method which involves subtraction by 1 (just as below, ‘n-1’), some online platforms may give an error if n is given the minimum value of integer or -2147483648. Subtraction by 1 gives integer overflow error in C++.
Below is the implementation of the above approach:
C++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
/* Function to check if x is power of 2*/
bool isPowerofTwo(long long n)
{
if (n <= 0)
return 0;
if ((n & (~(n - 1))) == n)
return 1;
return 0;
}
// Driver code
int main()
{
// Function call
isPowerofTwo(30) ? cout << "Yes\n" : cout << "No\n";
isPowerofTwo(128) ? cout << "Yes\n" : cout << "No\n";
return 0;
}
// This code is contributed by Sachin
Java
// Java program of the above approach
import java.io.*;
class GFG {
// Function to check if x is power of 2
static boolean isPowerofTwo(int n)
{
if (n == 0)
return false;
if ((n & (~(n - 1))) == n)
return true;
return false;
}
// Driver code
public static void main(String[] args)
{
// Function call
if (isPowerofTwo(30) == true)
System.out.println("Yes");
else
System.out.println("No");
if (isPowerofTwo(128) == true)
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by rajsanghavi9.
Python
# Python program of the above approach
# Function to check if x is power of 2*/
def isPowerofTwo(n):
if (n == 0):
return 0
if ((n & (~(n - 1))) == n):
return 1
return 0
# Driver code
if __name__ == "__main__":
# Function call
if(isPowerofTwo(30)):
print('Yes')
else:
print('No')
if(isPowerofTwo(128)):
print('Yes')
else:
print('No')
# This code is contributed by shivanisinghss2110
C#
// C# program of the above approach
using System;
public class GFG {
// Function to check if x is power of 2
static bool isPowerofTwo(int n)
{
if (n == 0)
return false;
if ((n & (~(n - 1))) == n)
return true;
return false;
}
// Driver code
public static void Main(String[] args)
{
// Function call
if (isPowerofTwo(30) == true)
Console.WriteLine("Yes");
else
Console.WriteLine("No");
if (isPowerofTwo(128) == true)
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code contributed by gauravrajput1
JavaScript
// javascript program of the above approach
// Function to check if x is power of 2
function isPowerofTwo(n)
{
if (n == 0)
return false;
if ((n & (~(n - 1))) == n)
return true;
return false;
}
if (isPowerofTwo(30) == true)
console.log("Yes");
else
console.log("No");
if (isPowerofTwo(128) == true)
console.log("Yes");
else
console.log("No");
Time complexity: O(1)
Auxiliary Space: O(1)
Similar Reads
Bitwise Algorithms
Bitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Sift and Right Shift. BasicsIntroduction to Bitwise Algorith
4 min read
Introduction to Bitwise Algorithms - Data Structures and Algorithms Tutorial
Bit stands for binary digit. A bit is the basic unit of information and can only have one of two possible values that is 0 or 1. In our world, we usually with numbers using the decimal base. In other words. we use the digit 0 to 9 However, there are other number representations that can be quite use
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if bot
7 min read
Bitwise Operators in Java
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
6 min read
Python Bitwise Operators
Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format. Note: Python bitwi
6 min read
JavaScript Bitwise Operators
In JavaScript, a number is stored as a 64-bit floating-point number but bitwise operations are performed on a 32-bit binary number. To perform a bit-operation, JavaScript converts the number into a 32-bit binary number (signed) and performs the operation and converts back the result to a 64-bit numb
5 min read
All about Bit Manipulation
Bit Manipulation is a technique used in a variety of problems to get the solution in an optimized way. This technique is very effective from a Competitive Programming point of view. It is all about Bitwise Operators which directly works upon binary numbers or bits of numbers that help the implementa
14 min read
What is Endianness? Big-Endian & Little-Endian
Computers operate using binary code, a language made up of 0s and 1s. This binary code forms the foundation of all computer operations, enabling everything from rendering videos to processing complex algorithms. A single bit is a 0 or a 1, and eight bits make up a byte. While some data, such as cert
5 min read
Bits manipulation (Important tactics)
Prerequisites: Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks for Competitive Programming Table of Contents Compute XOR from 1 to n (direct method)Count of numbers (x) smaller than or equal to n such that n+x = n^xHow to know if a number is a power of 2?Find XOR of all
15+ min read
Easy Problems on Bit Manipulations and Bitwise Algorithms
Binary representation of a given number
Write a program to print a Binary representation of a given number. Source: Microsoft Interview Set-3 Method 1: Iterative Method: For any number, we can check whether its 'i'th bit is 0(OFF) or 1(ON) by bitwise AND it with "2^i" (2 raise to i). 1) Let us take number 'NUM' and we want to check whethe
7 min read
Count set bits in an integer
Write an efficient program to count the number of 1s in the binary representation of an integer.Examples : Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bits Input : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits Recommended PracticeNumber of 1 BitsTr
15+ min read
Add two bit strings
Given two bit sequences as strings, write a function to return the addition of the two sequences. Bit strings can be of different lengths also. For example, if string 1 is "1100011" and second string 2 is "10", then the function should return "1100101". We strongly recommend that you click here and
13 min read
Turn off the rightmost set bit
Given an integer n, turn remove turn off the rightmost set bit in it. Input: 12Output: 8Explanation : Binary representation of 12 is 00...01100. If we turn of the rightmost set bit, we get 00...01000 which is binary representation of 8 Input: 7 Output: 6 Explanation : Binary representation for 7 is
7 min read
Rotate bits of a number
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put ba
11 min read
Compute modulus division by a power-of-2-number
Compute n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number. Input: 6 4 Output: 2 Explanation: As 6%4 = 2 Input: 12 8 Output: 4 Explanation: As 12%8 = 4 Input: 10 2 Output: 0 Explanation:As 10%2 = 0 Let ith bit from right is set in d. For getting n modulus d, we ju
6 min read
Find the Number Occurring Odd Number of Times
Given an array of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times. Find the number in O(n) time & constant space. Examples : Input : arr = {1, 2, 3, 2, 3, 1, 3}Output : 3 Input : arr = {5, 7, 2, 7, 5, 2, 5}Output : 5 Recommended
12 min read
Program to find whether a given number is power of 2
Given a positive integer n, write a function to find if it is a power of 2 or not Examples: Input : n = 4Output : YesExplanation: 22 = 4 Input : n = 42Output : NoExplanation: 42 is not a power of 2 Input : n = 1Output : YesExplanation: 20 = 1 Finding whether a given number is a power of 2 using Log
15+ min read
Find position of the only set bit
Given a number N having only one â1â and all other â0âs in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit '1' should be counted starting with 1 from the LSB side in the binary representation of the numb
15+ min read
Check for Integer Overflow
Write a "C" function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in "result" and returns 0. Otherwise, it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.Method 1 There can be overflo
8 min read
Find XOR of two number without using XOR operator
Given two integers, find XOR of them without using the XOR operator, i.e., without using '^' in C/C++. Examples : Input: x = 1, y = 2Output: 3Input: x = 3, y = 5Output: 6Approach:A Simple Solution is to traverse all bits one by one. For every pair of bits, check if both are the same, set the corresp
13 min read
Check if two numbers are equal without using arithmetic and comparison operators
Given two numbers, the task is to check if two numbers are equal without using Arithmetic and Comparison Operators or String functions. Method 1 : The idea is to use XOR operator. XOR of two numbers is 0 if the numbers are the same, otherwise non-zero. C/C++ Code // C++ program to check if two numbe
8 min read
Detect if two integers have opposite signs
Given two signed integers, write a function that returns true if the signs of given integers are different, otherwise false. For example, the function should return true -1 and +100, and should return false for -100 and -200. The function should not use any of the arithmetic operators. Let the given
8 min read
Swap Two Numbers Without Using Third Variable
Given two variables a and y, swap two variables without using a third variable. Examples: Input: a = 2, b = 3Output: a = 3, b = 2 Input: a = 20, b = 0Output: a = 0, b = 20 Input: a = 10, b = 10Output: a = 10, b = 10 Table of Content Using Arithmetic OperatorsUsing Bitwise XORBuilt-in SwapUsing Arith
6 min read
Russian Peasant (Multiply two numbers using bitwise operators)
Given two integers, write a function to multiply them without using multiplication operator.There are many other ways to multiply two numbers (For example, see this). One interesting method is the Russian peasant algorithm. The idea is to double the first number and halve the second number repeatedl
5 min read