尝试提交有关Leetcode的Pow(x,n)问题的解决方案时,我遇到了一个我不知道如何解决的错误。
double myPow(double x, int n)
{
if(n == 0) return 1; //Power of 0 return 1
int flag = 1;
double result;
if(n<0) flag = -1; //check if negative power
vector<double> myvec(n*flag,x); //create a vector length of the power, filled with our number x
result = accumulate(begin(myvec), end(myvec), 1.0, multiplies<>()); //multiply the elements of the vector
return flag > 0? result : 1/result;
}
我得到的错误是这样的:==33==ERROR: AddressSanitizer: allocator is out of memory trying to allocate 0x3fffffff8 bytes
#7 0x7f44d265d82f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
==33==HINT: if you don't care about these errors you may set allocator_may_return_null=1
如果我将“累积”行留为1而不是1.0,我得到的结果就好像double x是一个整数(例如2.1 ^ 3 = 8)。但是,当我将其更改为1.0以便从double中获取小数点时,会出现上述错误。有什么想法吗?
最佳答案
您正在分配过多的内存。您可以通过使用简单的for
循环获得相同的结果。
double res = 1;
for (int i = 1; i <= n; ++i)
res *= x;
虽然它可能会给您TLE。因此,您需要一个更好的算法。
关于c++ - 使用C++在LeetCode中的Pow(x,n)。地址 sanitizer 33,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62941969/