打印二进制排列的最快方法是什么?

发布于 2025-01-30 17:41:35 字数 776 浏览 4 评论 0原文

如果n = 3和r = 2,则在下面打印

110
101
011

我使用以下代码,但需要很长时间。

public void printBinaryPermutation(int n, int r)
{
    for(BigInteger i = new BigInteger("0"); i.compareTo(BigInteger.TWO.pow(n)) == -1; i = i.add(BigInteger.ONE))
    {
        String str = i.toString(2);
        while(str.length() < n)
        {
            str = "0" + str;
        }
        BigInteger amount = new BigInteger("0");
        for(char c : str.toCharArray())
        {
            if(c == '1')
            {
                amount = amount.add(BigInteger.ONE);
            }
        }
        if(amount.compareTo(new BigInteger(String.valueOf(r))) == 0)
        {
            System.out.println(str);
        }
    }
}

打印二进制排列的最快方法是什么?

If n=3 and r=2, print below

110
101
011

I'm using below code, But it takes a long time.

public void printBinaryPermutation(int n, int r)
{
    for(BigInteger i = new BigInteger("0"); i.compareTo(BigInteger.TWO.pow(n)) == -1; i = i.add(BigInteger.ONE))
    {
        String str = i.toString(2);
        while(str.length() < n)
        {
            str = "0" + str;
        }
        BigInteger amount = new BigInteger("0");
        for(char c : str.toCharArray())
        {
            if(c == '1')
            {
                amount = amount.add(BigInteger.ONE);
            }
        }
        if(amount.compareTo(new BigInteger(String.valueOf(r))) == 0)
        {
            System.out.println(str);
        }
    }
}

What is the quickest way to print Binary permutation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文