JS | 位元運算 Bitwise Operator

The following is my solution regarding a CodeSignal Problem addTwoDigits

1st Draft (61 Chars) makes use of reduce

addTwoDigits=n=>
  (""+n).split("").reduce((x,y)=>
    x+Number(y)
  ,0)

2nd Draft (49 Chars) deploys a recursive skill

f = addTwoDigits = n => n<10 
  ? n
  : n%10 + f(Math.floor(n/10))

It turns out I ignored the constraints that the number has only 2 digits… but I learnt a new trick from the best solutionsss

addTwoDigits = n => n%10 + n/10|0

After some researches, there are quite some magical uses for the | bitwise operator, e.g. x|0 can function as:

  1. Math.floor(x) for postive x

  2. parseInt(x) for string x

  3. 0 for many special x (NaN, Infinity, null, undefined, [], {} …)

HK7Math
HK7Math
數學愛好者

奧數 - 從梳理線索到悟通思路,重點在於屢敗屢試以及邏輯解難,與常規課程到大學數學都不盡相同,前者著重規範,後者則重嚴謹,而奧數的樂趣則在於發現規律、發現數學=)

Related