簡體   English   中英

如何在Java中將int移位4n倍?

[英]How can I shift a int by 4n times in java?

例如,有一個功能:

public int shift4N(int num, int n)
{
    num = num << n << n << n << n;
    return num;
}

有沒有多余的方法可以做到這一點? 但是不允許乘法...

任何幫助將不勝感激 :)

for循環對我來說似乎有點麻煩,為什么不只用移位代替乘法呢?

return num << (n << 2);

我不知道為什么不允許乘法,這是某種測驗嗎?

然后,只需使用“ num <<(n << 2)”,因為顯然允許移位。 (但請注意4 * n可能大於32)

如果我理解您的問題,一種替代方法是使用循環,

public int shift4N(int num, int n) {
  for (int i = 0; i < 4; i++) num <<= n;
  return num;
}

慣用Java:

interface ShiftByNStrategy { int shift(int num, int n); }

final class ShiftByNOnce extends ShiftingStrategy {
    @Override public int shift(int num, int n) { return num << n; }
}

final class RepeatedShiftByNStrategy implements ShiftByNStrategy {
    private final ShiftByNStrategy strategy;
    private final int times;

    RepeatedShiftByNStrategy(ShiftByNStrategy strategy, int times) {
        this.strategy = strategy;
        this.times = times;
    }

    @Override
    public int shift(int num, int n) {
        for (int i = 0; i < times; i++) num = strategy.shift(n);
        return num;
    }
}

final class ShiftByNStrategyFactory {
    private ShiftByNStrategyFactory() {}

    static ShiftByNStrategy shiftByNMultipleTimes(int times) {
        return new RepeatedShiftByNStrategy(new ShiftByNOnce(), times);
    }
}

所以你有

public int shift4N(int num, int n) {
    return ShiftByNStrategyFactory.shiftByNMultipleTimes(4).shift(num, n);
}

;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM