Leetcode Exercise 2

Reverse Integer

Wendy Wu
W-Learning Note
4 min readOct 29, 2018

--

Description

Given a 32-bit signed integer, reverse digits of an integer.

給一組32位元的有號整數(signed integer),將該整數的數字反轉過來。

Example

構思(old)

  1. 判斷數字是正/負數,複數的話先將數字轉為正整數
  2. 將數字轉成array後 →反轉 →轉回數字
  3. 根據原本的數字決定是否加上負號
  4. 檢查是否超過範圍[-2³¹, 2³¹-1],超過回傳0,未超過直接回傳

實作程式碼(old)

digits, digits(base):

Returns the array including the digits extracted by place-value notation with radix baseof int.

將數字轉換成base 進位制,沒有特別寫base的話,就是10進位制,這個method可以一舉達成轉換成array並反轉的步驟。舉例如下:

將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.

直接看下面的例子會比較清楚

inject

結果(old)

beats 66.23%

result(old)

2018/11/23 update

構思

  1. 先將數字轉為正整數→ 轉成string後→ 反轉→ 轉回數字
  2. 檢查是否超過範圍,超過回傳0
  3. 根據原本的數字決定是否加上負號

實作程式碼

結果

beats 100%

--

--