Leetcode Exercise 2
Reverse Integer
Published in
4 min readOct 29, 2018
Description
Given a 32-bit signed integer, reverse digits of an integer.
給一組32位元的有號整數(signed integer),將該整數的數字反轉過來。
Example
#1
Input: 123
Output: 321#2
Input: -123
Output: -321#3
Input: 120
Output: 21
構思(old)
- 判斷數字是正/負數,複數的話先將數字轉為正整數
- 將數字轉成array後 →反轉 →轉回數字
- 根據原本的數字決定是否加上負號
- 檢查是否超過範圍[-2³¹, 2³¹-1],超過回傳0,未超過直接回傳
實作程式碼(old)
# @param {Integer} x
# @return {Integer}
def reverse(x)
if x >= 0
x = x.digits
x = x.inject{|n, d| n * 10 + d}
else
x = x.abs
x = x.digits
x = x.inject{|n, d| n * 10 + d} * -1
end
if x >= 2147483647 || x <= -2147483648
return 0
else
return x
end
end
Returns the array including the digits extracted by place-value notation with radix
base
ofint
.
將數字轉換成base
進位制,沒有特別寫base
的話,就是10進位制,這個method可以一舉達成轉換成array並反轉的步驟。舉例如下:
12345.digits=> [5, 4, 3, 2, 1]#12345的二進制:11000000111001
12345.digits(2)=> [1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1]#12345的五進制:343340
12345.digits(5)=> [0, 4, 3, 3, 4, 3]
將array轉換成數字的方法,是參考這篇stackoverflow,inject的完整用法可以參考這裡,這邊使用到的是這一段:
If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element.
直接看下面的例子會比較清楚
結果(old)
beats 66.23%