Search code examples
c++algorithmpow

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


This is 338th question of Leetcode,Counting Bits.I think I finish it. But those code get a runtime error when input is 5? but why?

the question is : Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

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

Solution

  • I don't think this will hapen only to 5 but to all of your inputs. It is because you created num+1 elements in your binaryone vector by:

    vector<int> binaryone(num+1);

    and your loop while(i<=num+1) is indexing one past the end of the, zero based indexed, elements giving you a run-time error. If you have n elements, the index range would be from 0 to n-1.

    So change your loop condition to: while(i<num+1)