【发布时间】:2017-12-27 05:23:43
【问题描述】:
给定一个整数,我们需要找到整数的超位。
我们使用以下规则定义整数x 的超级数字:
如果x只有1个数字,那么它的超级数字是x
否则, 的上位等于x 的数字和的上位。这里,一个数字的数字和定义为它的数字之和。
例子:
super_digit(9875) = super_digit(9+8+7+5)
= super_digit(29)
= super_digit(2+9)
= super_digit(11)
= super_digit(1+1)
= super_digit(2)
= 2
任务:
你有两个数字n 和k。您必须计算p.p 的超级数字是在数字n 连接k 次时创建的。
我解决这个问题的代码如下所示。
#include <bits/stdc++.h>
#include <string>
#include <iostream>
#include <math.h>
using namespace std;
int superDigit(string n, int k)
{
int res=0;
for (int x = 0; x < n.length(); x++)
{
res += n[x] - '0';
}
res = k * res;
if (res < 10)
return res;
else
return superDigit(to_string(res),1);
}
int main() {
string n;
int k;
cin >> n;
cin >> k;
cout << superDigit(n, k)<< endl;
return 0;
}
代码似乎对所有小数字都正常工作,但是当n
是1e100000-1 和k 是100000,程序返回如下错误:
在抛出 'std::bad_alloc' 的实例后调用终止
what(): std::bad_alloc
我认为这是内存泄漏,但我该如何解决。泄漏发生在哪里?
【问题讨论】:
-
不是因为内存泄漏。它无法分配指定数量的内存。更多信息可以在这里找到:en.cppreference.com/w/cpp/memory/new/bad_alloc
-
使用调试器。它将在引发异常的点停止。非常有用。
-
很高兴知道这一点,但我该如何解决这个问题。
-
第一件事可能是消除递归。
-
无关:看来你不知道
#include <bits/stdc++.h>做了什么,所以我建议在Why should I not#include <bits/stdc++.h>? 变成坏习惯之前先阅读一下。
标签: c++ recursion memory-leaks