Select Page

Count of operations to make numbers equal by adding power of 2

Kashish Kumar
Published: July 7, 2022

  

import java.io.*;

  

class GFG {

      

    

    static int chk(int n, int bit)

    {

        return ((n & bit) != 0) ? 1 : 0;

    }

    

    

    

    public static int minMove(int X, int Y, 

                              int Z, int N)

    {

        int count = 0;

        boolean ans = true;

        for (int i = 0; i <= N; i++) {

  

            if (X == Y && Y == Z)

                break;

  

            

            int bit = (1 << i);

  

            int cnt

                = chk(X, bit) + chk(Y, bit) + chk(Z, bit);

  

            if (cnt == 0 || cnt == 3) {

                ans = false;

                break;

            }

            else if (cnt == 1) {

                if (chk(X, bit) == 1)

                    X += bit;

                else if (chk(Y, bit) == 1)

                    Y += bit;

                else

                    Z += bit;

            }

            else {

                if (chk(X, bit) == 0)

                    X += bit;

                else if (chk(Y, bit) == 0)

                    Y += bit;

                else

                    Z += bit;

            }

            count++;

        }

        return (ans && X == Y && Y == Z) ? count : -1;

    }

  

    

    public static void main(String[] args)

    {

        int X = 1, Y = 6, Z = 7, N = 30;

  

        

        System.out.println(minMove(X, Y, Z, N));

    }

}

Source: www.geeksforgeeks.org