【问题标题】:Ascertaining the highest power of 2 for a given integer确定给定整数的 2 的最高幂
【发布时间】:2016-07-28 20:53:33
【问题描述】:

当我使用 n = 64 运行此方法时,它给了我 x = 64,但不是运行 if 语句,而是运行 else 语句。实际答案需要是 32,但它返回 64。

/**
 * Complete the method to find the largest power of 2 less than the given number
 * Use a loop
 */

public class MathUtil {
  public int largestPowerOf2(int n) {
    // TODO: implement this method.
    int i = 0;
    while(n > 1) {
      n = n / 2;
      i ++;
    }
    System.out.printf("i = %d\n" , i);
    int x = (int)Math.pow(2,i);
    System.out.println(x);
    if(x == n) {
      return (int)Math.pow(2,i - 1);
    } else {
      return (int)Math.pow(2, i);
    }
  }
}

【问题讨论】:

  • 这听起来是一个让您熟悉调试器使用的好机会。在代码执行时单步执行并检查运行时值和行为。
  • 提示:执行if语句时n有什么值?当您回答了这个问题后,您就会知道代码为什么不起作用。干杯:)
  • 当您在 while 循环中连续执行 n = n / 2; 时,您认为 if(x == n) 将如何执行?
  • 你的算法在这里是错误的。它在整数已经是 2 的幂的情况下不起作用。这是一个边界问题。您需要在逻辑中更好地处理该边界。
  • 您在寻找Integer.highestOneBit(n - 1)吗?

标签: java debugging


【解决方案1】:

将一个测试整数乘以 2,直到得到一个不小于目标的数字,然后返回前一个数字

public int largestPowerOf2(int n){
    int mul = 1;
    int lastWorkingSolution = 0;
    while(true){
        if(mul >= n)
            return lastWorkingSolution;
        else{
            lastWorkingSolution=mul;
            mul*=2; 
        }
    }
}

【讨论】:

    【解决方案2】:

    这是做同样事情的一种相当简单的方法。只需循环 2 的幂,直到找到大于或等于 n 的幂。然后,只需从幂中减去 1 即可得到最后一个工作示例并返回该幂值。

    private static int largestPowerOf2(int n) {
        int power = 1;
        int value = (int)Math.pow(2, power);
        while (value < n) {
            power++;
            value = (int)Math.pow(2, power);
        }
    
        power--;
    
        return (int)Math.pow(2, power);
    }
    

    【讨论】:

      【解决方案3】:

      这应该可行。

      public int largestPowerOf2(int n){
      
          return Integer.highestOneBit(n-1);
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-20
        • 1970-01-01
        • 2021-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多