Compute modulus division by a power-of-2-number using Wrapper Class

Prerequisite : Compute modulus division by a power-of-2-number

Now as you know for getting n modulus 2k, we just need to return k bits(from LSB) in binary representation of n. In Java, you can use Wrapper class toBinaryString() method to get binary string representation of a number and getting substring from (str.length()-k) to end. And then by using Integer.parseInt(), you can convert this binary substring to number which is the remainder. Below is the Java program to demonstrate the same.

 // Java program to Compute modulus // division by a power-of-2-number    class Test {     // Driver method     public static void main(String[] args)      {         int num = 15;                    int two_power1 = 1;         int two_power2 = 2;         int two_power3 = 3;                    String binary = Integer.toBinaryString(num);         int len = binary.length();                    String rem1 = binary.substring(len-two_power1);         String rem2 = binary.substring(len-two_power2);         String rem3 = binary.substring(len-two_power3);                    int reme1 = Integer.parseInt(rem1, 2);         int reme2 = Integer.parseInt(rem2, 2);         int reme3 = Integer.parseInt(rem3, 2);                    System.out.println(num + "%" + "2^(" + two_power1 + ") = " + reme1);         System.out.println(num + "%" + "2^(" + two_power2 + ") = " + reme2);         System.out.println(num + "%" + "2^(" + two_power3 + ") = " + reme3);     } }

Output:

15%2^(1) = 1
15%2^(2) = 3
15%2^(3) = 7

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.