拆分二进制字符串,使其为5的幂

时间:2017-03-17 05:44:14

标签: java string

我正在尝试拆分二进制字符串,以便可以将字符串切割成最小的正整数,每个正整数为5的幂。如果没有这样的片段则返回-1。

public class Power {
    public int numsOfWays(String s) {
        long[] f = new long[s.length() + 1];
        f[0] = 0;
        for (int i = 1; i <= s.length(); ++i) {
            f[i] = Integer.MAX_VALUE;
            for (int j = 1; j <= i; ++j) {
                if (s.charAt(j - 1) == '0') {
                    continue;
                }
                int num = Integer.parseInt(s.substring(j - 1, i), 2);
                if (isPower(num)) {
                    f[i] = Math.min(f[i], f[j - 1] + 1);
                }
            }
        }
        return f[s.length()] == Integer.MAX_VALUE ? -1 : (int) f[s.length()];
    }

    private boolean isPower(long val) {
        if (val == 0) {
            return false;
        }
        int n = (int) (Math.log(val) / Math.log(5));
        return Math.pow(5, n) == val;
    }

    public static void main(String[] args) {

        Power b = new Power();
        System.out.println(b.numsOfWays("111011100110101100101110111"));
    }
}

我收到此错误: -

Exception in thread "main" java.lang.NumberFormatException: For input string: "11101110011010110010111011100000"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at abc.Power.numsOfWays(Power.java:13)
    at abc.Power.main(Power.java:33)

1 个答案:

答案 0 :(得分:0)

问题出在您的代码的第13行: 这一行:

int num = Integer.parseInt(s.substring(j - 1, i), 2);

有问题,因为int to handle的值太长了。

将其更改为:

long num = Long.parseLong(s.substring(j - 1, i), 2);

它应该有用。

编辑:整个代码如下所示:

public class Power {
    public int numsOfWays(String s) {
        long[] f = new long[s.length() + 1];
        f[0] = 0;
        for (int i = 1; i <= s.length(); ++i) {
            f[i] = Integer.MAX_VALUE;
            for (int j = 1; j <= i; ++j) {
                if (s.charAt(j - 1) == '0') {
                    continue;
                }
                long num = Long.parseLong(s.substring(j - 1, i), 2);
                if (isPower(num)) {
                    f[i] = Math.min(f[i], f[j - 1] + 1);
                }
            }
        }
        return f[s.length()] == Integer.MAX_VALUE ? -1 : (int) f[s.length()];
    }

    private boolean isPower(long val) {
        if (val == 0) {
            return false;
        }
        int n = (int) (Math.log(val) / Math.log(5));
        return Math.pow(5, n) == val;
    }

    public static void main(String[] args) {
        Power b = new Power();
        System.out.println(b.numsOfWays("111011100110101100101110111")); // 5
        System.out.println(b.numsOfWays("11111111111111111111111111111111111111111111111111")); // 50
    }
}

输出是:

5
50