In C bits, multiply by 3 and divide by 16

后端 未结 5 640
孤独总比滥情好
孤独总比滥情好 2020-12-29 17:46

A buddy of mine had these puzzles and this is one that is eluding me. Here is the problem, you are given a number and you want to return that number times 3 and divided by 1

5条回答
  •  难免孤独
    2020-12-29 18:03

    This seems to work (as long as no overflow occurs):

    ((num<<2)+~num+1)>>4
    

    Try this JavaScript code, run in console:

    for (var num = -128; num <= 128; ++num) {
      var a = Math.floor(num * 3 / 16);
      var b = ((num<<2)+~num+1)>>4;
      console.log(
        "Input:", num,
        "Regular math:", a,
        "Bit math:", b,
        "Equal: ", a===b
      );
    }
    

提交回复
热议问题