Ham*_*eem 0 java binary bit-manipulation
给出了一个由Q个字符组成的非空零索引字符串S。该字符串的周期最小
正整数P使得:
?Q / 2和S [K] = S [K + P]为0?K <Q?P.
例如,“ pepsicopepsicopep”的时间段为7。如果M是N的二进制表示形式的周期,则正整数M是正整数N的二进制周期。
例如,1651的二进制表示形式为“ 110011100111”。因此,其二进制周期为5。另一方面,102没有二进制周期,因为它的二进制表示是“ 1100110”,并且它没有周期。
考虑上述情况,并用Java编写一个函数,该函数将接受整数N作为参数。给定正整数N,函数将返回N的二进制周期。如果N没有二进制周期,则函数应返回?1。
下面,我还提供了我曾为之努力的解决方案,我想知道是否还有其他更好的解决方案?
public class BinaryPeriod {
public static void main(String[] args) {
System.out.println("\nEx1: " + getBinaryPeriodForInt(102));
System.out.println("\nEx2: " + getBinaryPeriodForInt(1651));
}
static int getBinaryPeriodForInt(int n) {
int[] d = new int[30];
int l = 0, res = -1;
while (n > 0) {
d[l] = n % 2;
n /= 2;
l++;
}
for (int p = 1; p < l; p++) {
if (p <= l / 2) {
boolean ok = true;
for (int i = 0; i < l - p; i++) {
if (d[i] != d[i + p]) {
ok = false;
break;
}
}
if (ok) {
res = p;
}
}
}
return res;
}
}
Run Code Online (Sandbox Code Playgroud)