Add ModuloPowerOfTwo algorithm (#5863)

This commit is contained in:
Hardik Pawar
2024-10-26 14:52:29 +05:30
committed by GitHub
parent fb85a4884f
commit 8551addbf2
3 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,28 @@
package com.thealgorithms.bitmanipulation;
/**
* This class provides a method to compute the remainder
* of a number when divided by a power of two (2^n)
* without using division or modulo operations.
*
* @author Hardvan
*/
public final class ModuloPowerOfTwo {
private ModuloPowerOfTwo() {
}
/**
* Computes the remainder of a given integer when divided by 2^n.
*
* @param x the input number
* @param n the exponent (power of two)
* @return the remainder of x divided by 2^n
*/
public static int moduloPowerOfTwo(int x, int n) {
if (n <= 0) {
throw new IllegalArgumentException("The exponent must be positive");
}
return x & ((1 << n) - 1);
}
}