Open
Conversation
oda
reviewed
May 30, 2025
| else: | ||
| break | ||
|
|
||
| int_digits = int(sign + str(int(only_digits_s))) |
| - 内部実装まで気にしたことがなかったが、調べてみると `str[i] - '0'` のようにASCII範囲の数字が1ずつ並んでいることを利用し、`num = num * 10 + 新しい桁 * sign` で既存の結果を10倍して新しい桁を加算することで、左から右へ数値を構築していくアルゴリズムはオーソドックスな方法らしいことがわかった | ||
| - しかしライブラリの実装[glibc](https://github.com/bminor/glibc/blob/master/stdlib/atoi.c)、[BSD libc](https://github.com/freebsd/freebsd/blob/master/lib/libc/stdlib/atoi.c)、[Newlib](https://github.com/bminor/newlib/blob/master/newlib/libc/stdlib/atoi.c)では、単純に `strtol()` を呼び出しているだけ | ||
| - cf. https://yohhoy.hatenadiary.jp/entry/20200604/p1 | ||
|
|
There was a problem hiding this comment.
Python だとあまり関係ないかもしれませんが、
C++ などだとオーバーフローをするかどうかを確認してから計算するような関数があったりします。
__builtin_add_overflow
stdckdint.h の ckd_add など。
hroc135
reviewed
Jun 14, 2025
| - `unicode.IsDigit()`関数で文字列が数字のみかどうか判定している | ||
| - 自分のコードは自前で実装したので、関数化するかPython組み込み型`str`の関数`str.isdigit()`を使うべきだった | ||
| - cf. https://docs.python.org/3/library/stdtypes.html#str.isdigit | ||
| - Goでは`s[index]`で文字列の特定位置にアクセスすると、その位置のUnicodeコードポイントが取得される |
There was a problem hiding this comment.
Go で s[index] とやると byte 型が返ってくるので、Unicode コードポイントではありません。
Unicode コードポイントを取得したい際は、rune 型(int32 の alias)を使う必要があります。
for i := 0; i < len(s); i++ {
b := s[i] // byte 型
...
for _, r := range s {
codepoint := r // rune 型
...
hroc135
reviewed
Jun 14, 2025
| return MAX_INT | ||
| idx += 1 | ||
|
|
||
| return num |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
8. String to Integer (atoi)
次回予告: 392. Is Subsequence