如何找到比给定数量少2的最大功率 [英] How to find the largest power of 2 less than the given number

查看:178
本文介绍了如何找到比给定数量少2的最大功率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到比给定数字少2的最大功率。

我卡住了,找不到任何解决方案。

I need to find the largest power of 2 less than the given number.
And I stuck and can't find any solution.

代码:

public class MathPow
{
   public int largestPowerOf2 (int n)
   {
        int res = 2;        
        while (res < n) {
                res =(int)Math.pow(res, 2);
        }

        return res;
   }
}

这不能正常工作。

测试输出:

Arguments Actual Expected
-------------------------
9         16     8       
100       256    64      
1000      65536  512     
64        256    32      

如何解决此问题?

推荐答案

更改 res =(int)Math.pow(res,2); 改为 res * = 2; 这将返回大于res的下一个2的幂。

因此,你所寻找的最终结果将在片尾结束后终于 res / 2

Change res =(int)Math.pow(res, 2); to res *= 2; This will return the next power of 2 greater than res.
The final result you are looking for will therefore finally be res / 2 after the while has ended.

为了防止代码溢出int值空间,你应该/可以将res的类型更改为double / long,任何可以保存高于int的值。最后你必须投一次。

To prevent the code from overflowing the int value space you should/could change the type of res to double/long, anything that can hold higher values than int. In the end you would have to cast one time.

这篇关于如何找到比给定数量少2的最大功率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆