gpt4 book ai didi

c++ - 将 int 转换为 unsigned long long

转载 作者:行者123 更新时间:2023-11-30 01:41:51 25 4
gpt4 key购买 nike

我正在解决一个问题,其中的任务是在用户提到的给定行输出帕斯卡三角形的结果。

https://leetcode.com/problems/pascals-triangle-ii/

我编写的解决方案在存储巨大的阶乘结果时存在问题。

vector<int> getRow(int rowIndex) {

vector<int> v;

int C = 1;
v.push_back(1);

for (int i = 1; i <= rowIndex; i++)
{
printf("%d ", C);
C = C * (rowIndex +1 - i) / i;
v.push_back(C);
}

return v;
}

在回答这些问题时,

What range of values can integer types store in C++

How many bytes is unsigned long long?

并通过其他一些资源,我进行了以下更改,这给了我所需的结果。

    C = (unsigned long long)C * (rowIndex +1 - i) / i;

因为“C”是 int 类型,而我的 vector v 存储 int,我想知道为什么转换 unsigned long long仍然给我有效的结果。

最佳答案

子表达式 C * (rowIndex +1 - i) 可以在除法之前溢出。通过将 C 转换为更大的数据类型,整个表达式将变为该类型,因此乘法不会溢出。然后在用 i 除法后,结果再次转换为 int,但由于除法,它在 int 的范围内。

请注意,这仅适用于您当前拥有的值。如果您继续使用更高的值,那么您迟早会遇到无法通过此类转换修复的溢出。

关于c++ - 将 int 转换为 unsigned long long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40714972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com