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

why this got a runtime error only if input is 5?

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

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

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 个问题上,而是会发生在你所有的输入上。这是因为您通过以下方式在 binaryone 向量中创建了 num+1 个元素:

vector<int> binaryone(num+1);

并且您的循环 while(i<=num+1) 正在索引一个从零开始的索引元素的末尾,给您一个 运行 时间错误。如果您有 n 个元素,则索引范围将从 0 to n-1.

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