Swap Bits Geeks For Geeks

Problem Link:


https://practice.geeksforgeeks.org/problems/swap-bits5726/1#


(It is also the problem of day for 29-03-2022)


Solution:

class Solution{

    

    int swapBits(int x, int p1, int p2, int n)

    {

        

        String s=String.format("%31s", Integer.toBinaryString(x)).replaceAll(" ", "0");

        //System.out.println(s);

        

        StringBuilder sb=new StringBuilder(s);

        /*

        for(int i=0;i<s.length();i++){

            sb.append(s.charAt(i));

        }*/

        //System.out.println(sb);

        int count=0;

        int a=30-p1;

        int b=30-p2;

        while(count!=n){

            char a1=sb.charAt(a);

            char a2=sb.charAt(b);

            sb.setCharAt(a,a2);

            sb.setCharAt(b,a1);

            a--;

            b--;

            count++;

        }

       // System.out.println(sb.toString());

        return Integer.parseInt(sb.toString(),2);

      

    }

}


Time Complexity: O(N)[GFG Time:0.2/2.0]

Space Complexity: O(1)

Auxiliary Space: O(N)[StringBuilder will copy the contents of the string so its length will be equal to string length.]

Total Test Cases:115

Approach Used:

Here we will convert first the integer number into binary. Even for conversion into binary, we will use string format as we have to make a string of length 31(not 32 as the 32nd bit represents MSB).

Now we will start traversing from the position given in question up to the limit and swap the characters one by one.

(Important thing to remember if you take p1 and p2 it means you are traversing binary string from the start while you need to traverse the string from the last so for that only you will do int a1=30-p1 and int a2=30-p2. Moreover, after every iteration you will move to MSB bit so you need to decrease the value of a1 and a2 simultaneously.)

As you go on covering rage we will swap the characters simultaneously and hence we get the final StringBuilder object which we will convert to integer value via conversion in string.



"Thanks For Reading.😇"

"Share Further To Increase KNowedge Treasure.😀"







Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks