c++ - 为什么仅当输入为 5 时才会出现运行时错误?

标签 c++ algorithm pow

这是Leetcode的第338题,Counting Bits,我想我做完了。 但是当输入为 5 时,这些代码会出现运行时错误?但是为什么?

问题是: 给定一个非负整数 num。对于 0 ≤ i ≤ num 范围内的每个数字 i,计算其二进制表示中 1 的数量,并将它们作为数组返回。

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> binaryone(num+1);
        binaryone[0]=0;
        if(0==num)
            return binaryone;
        binaryone[1]=1;
        if(1==num)
            return binaryone;
        int w = 1 ;
        int i = 2;
        while(i<=num+1)
        {
            if(i<(pow(2,w-1)+pow(2,w-2)))
            {
                binaryone[i]=binaryone[i-pow(2,w-2)];
            }
            else
            {
                if(i<=(pow(2,w)-1))
                {
                    binaryone[i]=binaryone[i-pow(2,w-2)]+1;
                }
                else
                {
                    if(i==pow(2,w))
                        {
                            w++;
                            binaryone[i]=binaryone[i-pow(2,w-2)];
                        }
                }
            }
            i++;
        }
        return binaryone;
    }
};

最佳答案

我认为这不会只发生在 5 个问题上,而是会发生在您的所有输入上。这是因为你创造了num+1 binaryone 中的元素 vector :

vector<int> binaryone(num+1);

和你的循环while(i<=num+1)正在对基于零的索引元素的末尾进行索引,这会给您带来运行时错误。如果你有 n元素,索引范围将从 0 to n-1 .

因此将循环条件更改为: while(i<num+1)

关于c++ - 为什么仅当输入为 5 时才会出现运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36915687/

相关文章:

c - 为什么我的阶乘程序可以运行,但我几乎相同的 pow 程序却无法运行?

c++ - 具有特征参数的模板特化函数

c++ - 使用 #pragma 删除基于 clang 检查的 clang 警告

algorithm - 最多排序 1000 万个 7 位数字。约束 : 1M RAM, 高速。几秒就好

algorithm - 查找具有特定长度且由特定字母组成的短语

c - 为什么 C 上的 Power int 不正确?

c++ - make 失败,返回错误 "cannot convert ‘std::istream {aka std::basic_istream<char>}’ 到 ‘bool’”

c++ - 如何检查字符串是否包含所有这些 : digits, 字母和特殊字符?

算法优化

c - 计算器中的指针不可用