1

好的,我以一种很好的方式完成了代码,并使用了递增 ++ 和递减 -- 运算符。

unsigned int atob(const char* input)
{

    int i = 0;

    while (input[i] == '0' || input[i] == '1') i++;

    unsigned result = 0;
    unsigned currentBit = --i;

    while ((*input == '0') || (*input == '1')) {
        char isCurrentBitSet = *input == '1';
        unsigned setValue = (isCurrentBitSet << currentBit--);
        result |= setValue;
        input++;
    }

    return result;
}

现在,我需要删除所有 dec(--)/inc(++),除了 while 语句底部的 input++。我对如何执行此实现感到困惑。

4

5 回答 5

4

干得好:

unsigned int atob(const char* input)
{
  unsigned result = 0;

  while ((*input == '0') || (*input == '1')) {
    result = (result << 1) | (*input++ - '0');
  }

  return result;
}

也节省了一些堆栈空间:)

于 2012-07-03T15:33:48.747 回答
2

通常的方法是从结果集开始为 0。然后对于输入的每个字符,将结果左移一位,or在当前位中,并重复直到到达输入字符串的末尾(或者不是 a01, 反正)。

于 2012-07-03T15:22:14.903 回答
1

决定彻底改变我的解决方案:

unsigned int atob(const char* input)
{
    unsigned val; 

    for (val = 0; *input; input++) {
        if (*input == '1') val = (val << 1) | 1;
        else if (*input == '0' ) val <<= 1;
        else break;
    }

    return val;
}
于 2012-07-03T15:32:34.710 回答
0

将 i++ 替换为 i = i + 1?这似乎很容易。

于 2012-07-03T15:24:02.757 回答
-1

考虑通过调用strtol来替换整个函数

于 2012-07-03T15:24:52.470 回答