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:
Math.floor(x) for postive x
parseInt(x) for string x
0 for many special x (NaN, Infinity, null, undefined, [], {} …)