java - 递归函数提升二进制ARRAY

标签 java arrays function recursion

如何使用递归函数提升二进制数组。 该函数接收二进制数组 V 并将 V 表示的数字的值增加到具有相同单位数的后续数字。如果操作可以执行,函数返回 true (java)

示例:

v = {0,0,0,1,1,0,0,1,1} => return true, v = {0,0,0,1,1,0,1,0,1}

我写的是:

public static boolean incrementSameOnes(int[] vec)  {
    boolean succ=false;
    int[] v=new int[vec.length-1];
    if(vec.length==1){
        return false;
    }
    if (vec[vec.length-1]==1 && vec[vec.length-2]==0)
    {
        vec[vec.length-2] = 1;
        vec[vec.length-1] = 0;
        System.out.print(Arrays.toString(vec));
        return true;
    }else {
        for(int j=0;j<vec.length-1;j++)
            v[j]=vec[j];
        succ=incrementSameOnes(v);  
        }
    return succ;
}

最佳答案

如果我理解正确的话,您想在二进制表示中找到具有相同数量的设置位的下一个更高的整数,对吗?如果是这样,我建议:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] x = { 1, 1, 1, 0, 1, 1, 0 };
        System.out.println("original: " + Arrays.toString(x));
        if (promote(x)) System.out.println("promoted: " + Arrays.toString(x));
        else System.out.println("not promotable");
    }

    private static boolean promote(int[] x) {
        // convert to integer value
        int value = 0;
        for (int i = 0; i < x.length; i++) {
            value += x[x.length - 1 - i] * (1 << i);
        }
        int newValue = value + 1, maxValue = 1 << x.length;
        int nBits = getNumberOfSetBits(value);

        // increase value until same amount of set bits found
        while (newValue < maxValue && getNumberOfSetBits(newValue) != nBits)
            newValue++;

        // convert back to array
        if (newValue < maxValue) {
            for (int i = 0; i < x.length; i++) {
                x[x.length - 1 - i] = (newValue & (1 << i)) >> i;
            }
            return true;
        } else {
            return false;
        }
    }

    // kung fu magic to get number of set bits in an int
    // see http://stackoverflow.com/a/109025/1137043
    private static int getNumberOfSetBits(int i) {
        i = i - ((i >> 1) & 0x55555555);
        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
        return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
    }
}

输出:

original: [1, 1, 1, 0, 1, 1, 0]
promoted: [1, 1, 1, 1, 0, 0, 1]

编辑:对于像您的示例中这样的 2D 数组,转换为 int 并返回数组格式看起来有点不同,但我建议使用相同的方法。

关于java - 递归函数提升二进制ARRAY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13697316/

相关文章:

javascript - 从数组转换为正确的对象格式

c++使用每个元素引用初始化数组?

javascript - 如何让控制台记录这个变量?

python - 获取二变量函数的所有可能结果 - Python 3

java - 如果在java中编译时替换Getter/Setter;如何才能实现他们的目的呢?

启动画面启动时出现 java.lang.UnsupportedOperationException

java - http客户端响应

javascript - 如何根据另一个数组中的相应值对一个数组进行排序?

javascript - 使用 jquery 函数添加/删除类

java - Jersey:可以从 ResourceInfo 获取 getResourceClass() 实现的接口(interface)吗?