admin管理员组文章数量:1530517
思路: 用vector保存结果的每一位
代码:
void extraLongFactorials(int n) {
if (n == 1) {
cout << 1 << endl;
return;
}
vector<int> digits(1, 1);
for (int curr(2); curr <= n; ++curr) {
auto digit_count = digits.size();
// Every digit times the number.
for (int i(0); i < digit_count; ++i) {
digits[i] *= curr;
}
// From the units to tenths, hundreds...
// Perform the carry.
for (int i(0); i < digit_count; ++i) {
auto carry = digits[i] / 10;
digits[i] = digits[i] % 10;
if (i != digit_count - 1) {
// Add the carry to the next digit.
digits[i + 1] += carry;
} else {
// New leftmost digit(s).
if (carry > 0) {
int & remaining(carry);
do {
auto digit = remaining % 10;
remaining /= 10;
digits.push_back(digit);
} while (remaining > 0);
}
}
}
}
// Print out the digits.
for (auto it = digits.rbegin(); it != digits.rend(); ++it) {
cout << *it;
}
}
本文标签: ExtraordinaryHackerRankfactoriallong
版权声明:本文标题:HackerRank: Extraordinary long factorial 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1725973742a1051103.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论