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.
davon ausgehen, dass:Die dezimale zip von zwei nichtnegativen ganzen Zahlen A und B einer ganzen Zahl C
• A und B ganze Zahlen sind im Bereich [0..100,000,000].
hier ist meine Lösung, aber ich habe ein Array gebunden expection
so versuchte ich die ganze Zahl in String zu konvertieren, so dass ich sie verarbeiten, und die Ziffern zusammen zu fügen.
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());
}
Für einen einfachen Test nur eingestellt 'A_' eine längere Zeichenfolge als' B_' und Schritt durch den Code und zu sehen zu sein, was passiert. Hinweis: Achten Sie auf den Zustand der for-Schleife. – NathanOliver
Warum haben Sie dieses C markiert, wenn es sich um eine C++ - Zuweisung handelt? Was ist IntToString? Und was macht es? –
Ihr erster Test kann um ein Drittel verlängert werden, wenn: 'if (100000000 Ped7g