Java 使用封装类计算模数除以2的幂数
在Java中,你可以使用Wrapper类的toBinaryString()方法来获得一个数字的二进制字符串表示,并获得从(str.length()-k )到最后的子串。然后通过使用Integer.parseInt(),你可以将这个二进制子串转换为数字,也就是余数。下面是一个Java程序来证明这一点。
// 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);
}
}
输出:
15%2^(1) = 1
15%2^(2) = 3
15%2^(3) = 7