如何找到划分数字的尺寸K的计数

发布于 2025-01-29 01:45:29 字数 681 浏览 3 评论 0原文

给出了数字n 在划分数字的数字中找到大小x的子数量的计数。

例如,如果数字为250 x = 2 答案是2 AS 250%25 == 0 和250%50 == 0。

谁能帮助我使用CPP代码?

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

这显示了运行时错误

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%25==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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

审判长 2025-02-05 01:45:29

您有很多问题。首先,为您的变量使用简单的字母意味着我们不知道这些变量的用途。使用有意义的名称。

其次,这是:

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

您对方法称为k。您现在已经遮蔽了它。从技术上讲,您可以做到这一点,但这确实是一个非常坏的习惯。

但是真正的问题在这里:

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

我是初始化为0,直到第一次运行后才更改。因此,您实际上是在字符串开始之前删除角色。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文