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.
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 firstname.lastname@example.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.
- Java.util.BitSet class methods in Java with Examples | Set 2
- More restrictive access to a derived class method in Java
- java.lang.Character class methods | Set 1
- Static class in Java
- Inner class in java
- BigInteger Class in Java
- Scanner Class in Java
- Primitive Wrapper Classes are Immutable in Java
- Java.Lang.Float class in Java
- Does JVM create object of Main class (the class with main())?
- Difference between Scanner and BufferReader Class in Java
- Myth about the file name and class name in Java
- Arrays class in Java
- Date class in Java (With Examples)
- How to create Immutable class in Java?