jayati

Rightmost different bit

Sep 29th, 2023
1,316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. //{ Driver Code Starts
  2. //Initial Template for C++
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7.  
  8. // } Driver Code Ends
  9. //User function Template for C++
  10.  
  11. class Solution
  12. {
  13.     public:
  14.     //Function to find the first position with different bits.
  15.     int posOfRightMostDiffBit(int m, int n)
  16.     {
  17.         // Your code here
  18.         int ans=-1;
  19.         int i=1;
  20.         if(m==0 || n==0)
  21.         {
  22.             if(n==0)
  23.             {
  24.                 while(m!=0)
  25.                 {
  26.                     if((m&1)!=(n&1))
  27.                     {
  28.                         ans=i;
  29.                         break;
  30.                     }
  31.                     m=m>>1;
  32.                     i++;
  33.                 }
  34.             }
  35.             else if(m==0)
  36.             {
  37.                 while(n!=0)
  38.                 {
  39.                     if((m&1)!=(n&1))
  40.                     {
  41.                         ans=i;
  42.                         break;
  43.                     }
  44.                     n=n>>1;
  45.                     i++;
  46.                 }
  47.             }
  48.         }
  49.         else
  50.         {
  51.             while(m!=0 || n!=0)
  52.         {
  53.             if((m&1)!=(n&1))
  54.             {
  55.                 ans=i;
  56.                 break;
  57.             }
  58.             m=m>>1;
  59.             n=n>>1;
  60.             i++;
  61.         }
  62.            
  63.         }
  64.        
  65.         return ans;
  66.     }
  67. };
  68.  
  69. //{ Driver Code Starts.
  70.  
  71. // Driver Code
  72. int main()
  73. {  
  74.     int t;
  75.     cin>>t; //input number of testcases
  76.     while(t--)
  77.     {
  78.          int m,n;
  79.          cin>>m>>n; //input m and n
  80.          Solution ob;
  81.          cout << ob.posOfRightMostDiffBit(m, n)<<endl;
  82.     }
  83.     return 0;    
  84. }
  85. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment