【问题标题】:How to avoid using ++ and -- operators如何避免使用 ++ 和 -- 运算符
【发布时间】:2012-07-03 15:17:35
【问题描述】:

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

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++。我对如何执行此实现感到困惑。

【问题讨论】:

  • 你需要摆脱增量和减量的原因是什么?
  • @EvilTeach:我只是在猜测,但我想说是他的老师(教授,随便)间接地试图推动他考虑不同的解决方案。
  • 有点接近。不过我只是为了学习!

标签: c bit-manipulation


【解决方案1】:

给你:

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

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

  return result;
}

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

【讨论】:

    【解决方案2】:

    通常的方法是从结果集开始为 0。然后对于输入的每个字符,将结果左移一位,or 在当前位,并重复直到到达输入字符串的末尾 (或01 以外的其他东西,无论如何)。

    【讨论】:

      【解决方案3】:

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

      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;
      }
      

      【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 根本无法使用算术。所以,没有。
      • 您的问题也许应该包括该陈述? (提示)
      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-01
        • 1970-01-01
        • 2021-07-11
        • 2015-05-15
        • 1970-01-01
        • 1970-01-01
        • 2019-08-20
        • 1970-01-01
        相关资源
        最近更新 更多