Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Tuesday, August 22, 2017

Rightmost different bit


Problem :

Given two numbers x and y. Write a program to find the position of rightmost different bit in binary representation of numbers.

Expl:

XOR sets bit where bit of both numbers are different so we will xor and find position of 1st set bit suing shift and & operator

Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
 {
     public static void setbit(int x)
     {
         int count=1;
         int i=0;
         while(true)
         {
            // System.out.println(x&(1<<i));
             if((x&(1<<i))>0) // we are checking by shifting 1 to nth position and if number //also have same bit (1) it will be >0
             {
                 System.out.println(count);
                 return;
             } 
             ++i;
             ++count;
         }
     }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
   int n=ab.nextInt();
   int k=ab.nextInt();
   setbit(n^k);
}
}
}

0 Comments:

Post a Comment

Stats