有人可以给我这个算法的例子

时间:2013-03-21 10:32:38

标签: c algorithm

这个算法用Write great code Vol 1 book编写,用于将十进制数字串转换为整数值:

  1. 将变量初始化为零;这将保留最终价值。
  2. 如果字符串中没有更多数字,则算法完成, 并且变量保存数值。
  3. 从字符串中获取下一个数字(从左到右)。
  4. 将变量乘以10,然后添加步骤3中提取的数字。
  5. 转到第2步并重复。
  6. 我不知道转换是如何发生的。请举例说明。

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

这是您的标准字符串到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.

答案 2 :(得分:1)

考虑字符串“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