Skip to content

Conversation

@skypenguins
Copy link
Owner

8. String to Integer (atoi)

次回予告: 392. Is Subsequence

@skypenguins skypenguins self-assigned this May 30, 2025
else:
break

int_digits = int(sign + str(int(only_digits_s)))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

出題意図はここの部分を作って欲しいという問題に思いますね。

- 内部実装まで気にしたことがなかったが、調べてみると `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

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python だとあまり関係ないかもしれませんが、
C++ などだとオーバーフローをするかどうかを確認してから計算するような関数があったりします。
__builtin_add_overflow
stdckdint.h の ckd_add など。

- `unicode.IsDigit()`関数で文字列が数字のみかどうか判定している
- 自分のコードは自前で実装したので、関数化するかPython組み込み型`str`の関数`str.isdigit()`を使うべきだった
- cf. https://docs.python.org/3/library/stdtypes.html#str.isdigit
- Goでは`s[index]`で文字列の特定位置にアクセスすると、その位置のUnicodeコードポイントが取得される
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

return MAX_INT
idx += 1

return num
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

シンプルで読みやすかったです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants