作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
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.
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/
我是一名优秀的程序员,十分优秀!