VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-whether-two-numbers-differ-one-bit-position/

⇱ Check whether the two numbers differ at one bit position only - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check whether the two numbers differ at one bit position only

Last Updated : 15 Jun, 2022

Given two non-negative integers a and b. The problem is to check whether the two numbers differ at one bit position only or not.
Examples: 
 

Input : a = 13, b = 9
Output : Yes
(13)10 = (1101)2
(9)10 = (1001)2
Both the numbers differ at one bit position only, i.e,
differ at the 3rd bit from the right.

Input : a = 15, b = 8
Output : No


 


Approach: Following are the steps:
 

  1. Calculate num = a ^ b.
  2. Check whether num is a power of 2 or not. Refer this post.


 

Output: 
 

Yes


Time Complexity: O(1).

Auxiliary Space: O(1).
 

Comment
Article Tags: