c++ - 使用C++在LeetCode中的Pow(x,n)。地址 sanitizer 33

标签 c++ algorithm out-of-memory

尝试提交有关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/

相关文章:

c++ - istream 对象上的 scanf

java - 从一个更大的列表中找到 2 个相等和的列表

android - Glide、Recyclerview 和 OOM

java - 配置 eclipse/java 以最大限度地提升性能

c++ - 将整数字符串转换为 int 的最简单方法

c++ - SDL_RenderPresent() 不等待 vsync - 如何等待?

c++ - sprintf 的内部工作

javascript - 将两个多维数组映射到一个对象中

algorithm - 按此向量中映射的成员对对象向量进行排序

java - 如何合并来自不同服务的 WSDL 和 XSD 的公共(public)部分?