Write great code Vol 1 bookで書かれたこのアルゴリズムは、10進数の文字列を整数値に変換するためのものです。
- 変数をゼロで初期化します。これは最終的な値を保持します。
- 文字列にこれ以上数字がない場合、アルゴリズムは完了し、変数は数値を保持します。
- 文字列から次の桁(左から右へ)をフェッチします。
- 変数に10を掛けてから、手順3で取得した桁を加算します。
- 手順2に進み、繰り返します。
変換がどのように行われるのかわかりません。この例を挙げてください。
/* warning: naive and unsafe implement. don't use it for important projects */
int strtod(const char *str)
{
int ret = 0;
while (*str)
ret = ret * 10 + *str++ - '0';
return ret;
}
文字列「1134」を考えてみましょう
String Variable
()1134 0
(1)134 0 * 10 + 1 = 1
1(1)34 1 * 10 + 1 = 11
11(3)4 11 * 10 + 3 = 113
113(4) 113 * 10 + 4 = 1134
これは、標準の string から int への変換アルゴリズムです。
char *s = "12345";
int res = 0; // 1. Initialize a variable with zero
while (*s) { // 2. If there are no more digits in the string...
int d = (*s++ - '0'); // 3. Fetch the next digit
res = 10*res + d; // 4. Multiply the variable by ten, and then...
} // 5. Go to step 2 and repeat.