Conversation
|
問題文の英語の誤読も目立った。文字列から数字を抽出してそれに関してint変換するものと勘違いしていた時間もあった |
| # is_number -> extract_number(integer部分を抜き取る) -> 数字化処理 | ||
|
|
||
| def char_is_number(char: str)->bool: | ||
| if ord(char) >= ord("0") and ord("9") >= ord(char): |
There was a problem hiding this comment.
直後に return True/False を行っています。この場合、 if 文の条件式をそのまま返したほうがシンプルになると思います。
また、不等号の向きは
- 比較される側を常に左に置く
- 数直線上に一直線に並ぶよう、左から右に、小さいほうから大きいほうに並べる
等の流派があります。複数の書き方で書けるようにして置き、チーム内でよく書かれる書き方で書けるようにしておくとよいと思います。
今回の場合は、 return ord("0") <= ord(char) and ord(char) <= ord("9") あたりが良いと思います。
There was a problem hiding this comment.
pythonならreturn ord("0") <= ord(char) <= ord("9")もできますね。
この問題だと、isdigitを使ってもいいです。
There was a problem hiding this comment.
一応, ここでの会話(cheeseNA/leetcode#5 (comment)) を見てisdigitは使わない方向にしてみました。
|
|
||
|
|
||
| class Solution: | ||
| def myAtoi(self, s: str) -> int: |
There was a problem hiding this comment.
myAtoi() は実質 string_to_integer() のラッパーになっているように思います。あえてラップする意味はないと思います。 string_to_integer() の中身をここに書いてしまったほうが良いと思います。
| return 0 | ||
|
|
||
| current_pointer = 0 | ||
| while current_pointer < len(s): |
There was a problem hiding this comment.
whlie while current_pointer < len(s) and s[current_pointer] == " ": で良いと思います。
| # is_number -> extract_number(integer部分を抜き取る) -> 数字化処理 | ||
|
|
||
| def char_is_number(char: str)->bool: | ||
| if ord(char) >= ord("0") and ord("9") >= ord(char): |
There was a problem hiding this comment.
pythonならreturn ord("0") <= ord(char) <= ord("9")もできますね。
この問題だと、isdigitを使ってもいいです。
| if len(s) == 0: | ||
| return 0 | ||
|
|
||
| current_pointer = 0 |
There was a problem hiding this comment.
| return False | ||
|
|
||
| def string_to_integer(s: str)->int: | ||
| if len(s) == 0: |
| while current_pointer < len(s) and char_is_number(s[current_pointer]): | ||
| abs_value *= 10 | ||
| abs_value += ord(s[current_pointer]) - ord("0") | ||
| if abs_value * sign > INT_MAX: |
There was a problem hiding this comment.
もし32-bitのintしか使えない状況だったら、どうやって判定するかも考えてみてもいいかもしれません。
There was a problem hiding this comment.
計算前のabs_valueの値を取っておいて, 計算後に符号が変わっていたらオーバーフローしているので, signに従ってINT_MAXかINT_MINを出力という感じでしょうか
There was a problem hiding this comment.
signed intのオーバフーローは、C++ではundefined behaviorみたいです。unsigned intを使えば簡単に確認できますが、もしintしか使えないという制約のもとでは、10倍して次の数字を足す前に確認できそうです。
https://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c
There was a problem hiding this comment.
ちょうど今C++でも書いていたんですが, runの時点panicを引き起こしました
There was a problem hiding this comment.
Rustなどだとオーバーフロー制御があるので書きやすいので, そちらでも時間があったら書いてみます
| break | ||
| current_pointer += 1 | ||
|
|
||
| if current_pointer == len(s): |
There was a problem hiding this comment.
while-else文知らなかったです...
https://leetcode.com/problems/string-to-integer-atoi/?envType=list&envId=xo2bgr0r
問題