Home > Back-end >  How to find the count of sub numbers of size k which divide the number
How to find the count of sub numbers of size k which divide the number

Time:05-15

Given a number n Find the count of the sub numbers of size x in a number num which divides num.

For example, if the number is 250 and x=2 the answer will be 2 as 250%==0 and 250 % 50==0.

Can anyone help me out with the cpp code ?

class Solution {
public:
    int divisorSubstrings(int num, int k) {
        string s=to_string(num);
        int count=0;
        int i=0;
        int j=k-1;
        string temp="";
        for(int k=i;k<=j;k  )
        {
            temp.push_back(s[k]);
        }
        while(j<s.length())
        {
            if(num%stoi(temp)==0)
                count  ;
            temp.erase(temp.begin()   i-1);
            j  ;
            i  ;
            temp.push_back(s[j]);
        }
        return count;
    }
};

this is showing runtime error

CodePudding user response:

You have a number of problems. First, using simple letters for your variables means we don't have a clue what those variables are for. Use meaningful names.

Second, this:

    for(int k=i;k<=j;k  )

You have an argument to your method called k. You've now shadowed it. Technically, you can do that, but it's a really really bad habit.

But the real problem is here:

        temp.erase(temp.begin()   i-1);

i is initialize to 0 and never changed until AFTER this line runs the first time. So you're actually erasing a character before the start of the string.

  • Related