gpt4 book ai didi

c++ - 两个非负整数A和B的十进制zip是整数C

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:17:44 31 4
gpt4 key购买 nike

The decimal zip of two non-negative integers A and B is an integer C whose 
decimal representation is created from the decimal representations
of A and B as follows:

• the first (i.e. the most significant) digit of C is the first digit of A;
• the second digit of C is the first digit of B;
• the third digit of C is the second digit of A;
• the fourth digit of C is the second digit of B;
• etc.

If one of the integers A and B runs out of digits, the remaining digits of
the other integer are appended to the result.

The decimal representation of 0 is assumed to be "0".

For example, the decimal zip of 12 and 56 is 1526.
The decimal zip of 56 and 12 is 5162.
The decimal zip of 12345 and 678 is 16273845.
The decimal zip of 123 and 67890 is 16273890.

Write a function: function solution(A, B); that, given two non-negative
integers A and B, returns their decimal zip.

The function should return -1 if the result exceeds 100,000,000.

For example, given A = 12345 and B = 678 the function should return
16273845, as explained above.

假使,假设:

•A和B是[0..100,000,000]范围内的整数。

这是我的解决方案,但我得到了数组约束的期望

因此,我尝试将整数转换为字符串,以便对其进行处理,然后将数字加在一起。
int solution(int A, int B) {
// write your code in C++11 (g++ 4.8.2)
if (A < 0 || A > 100000000) return -1;
if (B < 0 || B > 100000000) return -1;

string A_ = IntToString(A);
string B_ = IntToString(B);
string output = "";

for (int i = 0; i < A_.size() || i < B_.size(); i++) {

if (A_[i]) {
output[i] = output[i] + A_[i];
}

if (B_[i]) {
output[i] = output[i] + B_[i];
}
}

return atoi(output.c_str());
}

最佳答案

仅当for达到最大字符串的大小时,才会停止i循环。但是您继续使用i作为两个字符串的索引。因此,您将超出较短的范围,从而导致错误。

代替:

    if (A_[i])

您可能想要:
    if (i < A_.size())

关于c++ - 两个非负整数A和B的十进制zip是整数C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38271587/

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