Conversation
| end | ||
|
|
||
| max_value = 2 ** 31 - 1 | ||
| min_value = (-1) * 2 ** 31 |
There was a problem hiding this comment.
コメントありがとうございます!
Rubyはメソッドの外側でしか定数を定義できないので変数にしています。
メソッドの外に出してしまうと定数としては定義できますがスコープが広くなるので悩ましいですね…
| index += 1 | ||
| end | ||
| if str_without_left_space.start_with?("+") | ||
| index += 1 |
There was a problem hiding this comment.
indexを進める代わりに、新しい文字列の変数を定義して、最後のwhile文をその文字列でfor_each_charを行う処理に変えてもよいと思いました。
| digit = str_without_left_space[index].to_i | ||
|
|
||
| if result > (max_value - digit) / 10 | ||
| return sign == 1 ? max_value : min_value |
There was a problem hiding this comment.
"-2147483648" (min_value) が入力されたら Rounding の対象ではないが、この行で return されるように思いました。正しい値を返せていますが、少し引っかかりました。
There was a problem hiding this comment.
ありがとうございます。
確かに改めて見るとMIN_VALUEなのにオーバーフロー扱いしているように見えるので気持ち悪いですね。
There was a problem hiding this comment.
# @param {String} str
# @return {Integer}
def my_atoi(str)
str_without_left_space = str.lstrip
index = 0
sign = 1
if str_without_left_space.start_with?("-")
sign = -1
index += 1
end
if str_without_left_space.start_with?("+")
index += 1
end
max_value = 2 ** 31 - 1
min_value = (-1) * 2 ** 31
limit = (sign == 1) ? max_value : 2 ** 31
result = 0
while index < str_without_left_space.size && str_without_left_space[index].between?("0", "9")
digit = str_without_left_space[index].to_i
if result > (limit - digit) / 10
return sign == 1 ? max_value : min_value
end
result = result * 10 + digit
index += 1
end
result * sign
endこっちの方が良いかもしれません
There was a problem hiding this comment.
絶対値の上限を正負で分けたということですね。自分だったら absolute_value_limit のようにします。
改善案がなく恐縮ですが、2 ** 31 とハードコーディングしている箇所が増えたのは保守性が落ちてしまっているかもしれないと思いました。
There was a problem hiding this comment.
absolute_value_limit = (sign == 1) ? max_value : (-1) * min_value
とするとかですかね。
解いた問題
8. String to Integer (atoi)
使用言語
Ruby
次に解く問題
https://leetcode.com/problems/zigzag-conversion/description/