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

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

本文关键字:运行时错误 5时 输入 为什么      更新时间:2023-10-16

这是Leetcode的第338个问题,计数位。我想我完成了。但是当输入为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上,而是会发生在所有输入上。这是因为您通过以下方式在binaryone矢量中创建了num+1元素:

vector<int> binaryone(num+1);

而您的循环while(i<=num+1)正在索引一个超过以零为基础的索引元素末尾的元素,这会给您带来运行时错误。如果有n元素,则索引范围将从0 to n-1开始。

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