Swap two nibbles in a byte | Practice | GeeksforGeeks

Given a number N, swap the two nibbles in it and find the resulting number. 
 
Example 1:
Input:
N = 100
Output:
70
Explanation:
100 in binary is 01100100, 
two nibbles are (0110) and (0100)
If we swap the two nibbles, we get
01000110 which is 70 in decimal


Example 2:
Input:
N = 129
Output:
24
Explanation:
129 in binary is 10000001, 
two nibbles are (1000) and (0001)
If we swap the two nibbles, we get
00011000 which is 24 in decimal

Your Task:
You don't need to read input or print anything. Your task is to complete the function swapNibbles() which takes an integer N as input parameters and returns an integer after swapping nibbles in the binary representation of N.
 
Expected Time Complexity: O(1)
Expected Space Complexity: O(1)
 
Constraints:
0 ≤ N ≤ 255
0
vishnu12654 days ago
def swapNibbles (self, N):
        return (N & 15)<<4 | (N & 240)>>4;

+1
sandeepkmrnayak3 weeks ago
Simple C++ Solution:
unsigned char ans = x<<4 | x>> 4;
return ans;
0
abcool1 month ago
Simple solution:
static int swapNibbles(int N) {
        String temp = Integer.toBinaryString(N);
        while(temp.length()<8)
            temp="0"+temp;
        String s1 = temp.substring(0,4);
        String s2 = temp.substring(4,temp.length());
        Integer ans = Integer.parseInt(s2+s1,2);
        return ans;
    }
0
aroopghosh5532 months ago
class Solution{
public:
    int swapNibbles(unsigned char x){
        int ans = 0;
        for(int i = 0; i < 4; i++){
            ans = ans + ((x >> i) & 1) * pow(2, i + 4);
        }
        for(int i = 4; i < 8; i++){
            ans = ans + ((x >> i) & 1) * pow(2, i - 4);
        }
        return ans;
    }
};
+1
prateekkasaudhan1232 months ago
Nibble is a four-bit aggregation. There are two nibbles in a byte.
Take the example of 100-:
100 in binary is 01100100, 
two nibbles are (0110) and (0100)
If we swap the two nibbles, we get
01000110 which is 70 in decimal.
 
class Solution{   static int swapNibbles(int N) {       //code here       int m =(240 & (N<<4));       int p = ((N>>4));       return (m+p);   }}
0
krishnakshirsagar412 months ago
#User function Template for python3class Solution:   def swapNibbles (self, N):       # code here               str1 = ""       str1 = (bin(N).replace("0b", ""))       list1 = []       for i in str1:           list1.append(i)       k = 8 - len(list1)              for i in range(0,k):           list1.insert(0, "0")       
       ans = []       ans.extend(list1[4:])       ans.extend(list1[:4])              str2 = ''.join(ans)              return int(str2,2)
0
abythankachan3142 months ago
Time taken : 0.0/1.0
PYTHON CODE :
#python3
class Solution:
   def swapNibbles (self, N):
       binary= str(format(N,"08b"))
       l1=[]
       l2=[]
       ans=""
       for t in range(0,4):
           l1.append(binary[t])
       for j in range(4,len(binary)):
           l2.append(binary[j])
       for k in l2:
           ans+=str(k)
       for u in l1:
           ans+=str(u)
       return int(ans,2)
       # code here
#{ 
#  Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__': 
   t = int (input ())
   for _ in range (t):
       N = int(input())
     
       ob = Solution()
       print(ob.swapNibbles(N))
# } Driver Code Ends
+1
madhukartemba3 months ago
EASY JAVA SOLUTION:
//User function Template for Java
class Solution{
    static int swapNibbles(int N) {
        //code here
        int h1 = N & 15;  // N AND 00001111
        int h2 = N & 240;  // N AND 11110000
        
        return (h1<<4) + (h2>>4);  //Exchange positions of h1 and h2;
        
    }
}
+1
mukulvyasg3 months ago
#python 
 
class Solution:
   def swapNibbles (self, N):
       b = bin(N)
       b = b.replace("0b","0"*(10-len(b)))
       b = b[4:]+b[:4]
       return int(b,2)
+5
ayerajkumar3 months ago
A nibble is a four-bit aggregation, or half an octet. There are two nibbles in a byte. Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal.
 
//User function Template for Javaclass Solution{   static int swapNibbles(int N) {   return ((N & 0x0F) << 4 | (N & 0xF0) >> 4);   }}
 
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.