java 在java中写一个函数来找到一个正整数N的二进制周期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33996259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:23:24  来源:igfitidea点击:

write a function in java to find the binary period of a positive integer N

javabinarybit-manipulation

提问by Hamzeen Hameem

A non-empty zero-indexed string S consisting of Q characters is given. The period of this string is the smallest

给出了一个由 Q 个字符组成的非空零索引字符串 S。这个字符串的周期是最小的

positive integer P such that:

正整数 P 使得:

P ≤ Q / 2 and S[K] = S[K+P] for 0 ≤ K < Q ? P.

P ≤ Q / 2 且 S[K] = S[K+P] 对于 0 ≤ K < Q ? P。

For example, 7 is the period of “pepsicopepsicopep”. A positive integer M is the binary period of a positive integer N if M is the period of the binary representation of N.

例如,7 是“pepsicopepsicopep”的时期。如果 M 是 N 的二进制表示的周期,则正整数 M 是正整数 N 的二进制周期。

For example, 1651has the binary representation of "110011100111". Hence, its binary period is 5. On the other hand, 102 does not have a binary period, because its binary representation is “1100110” and it does not have a period.

例如,1651的二进制表示为“110011100111”。因此,它的二进制周期是 5。另一方面,102没有二进制周期,因为它的二进制表示是“1100110”,它没有周期。

Consider above scenarios & write a function in Java which will accept an integer N as the parameter. Given a positive integer N, the function returns the binary period of N. The function should return ?1 if N does not have a binary period.

考虑上述场景并用 Java 编写一个函数,该函数将接受一个整数 N 作为参数。给定一个正整数 N,函数返回 N 的二进制周期。如果 N 没有二进制周期,函数应该返回 ?1。

Below I have included the solution I worked for it as well & I would like to know whether there exists any other better ways to solve it?

下面我也包括了我为它工作的解决方案,我想知道是否还有其他更好的方法来解决它?

回答by Hamzeen Hameem

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;
    }
}