Created
May 23, 2015 02:51
-
-
Save luckypapa/2ad7f0fce6ec0b58a06c to your computer and use it in GitHub Desktop.
No. 55 - Translating Numbers to Strings : solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //http://codercareer.blogspot.kr/2014/09/no-55-translating-numbers-to-string.html | |
| #include <iostream> | |
| #include <string> | |
| #include <assert.h> | |
| using namespace std; | |
| int getTransCount(string number) { | |
| if (atoi(number.c_str()) <= 0) | |
| return 0; | |
| int length = number.length(); | |
| int counts[length] = {0,}; | |
| for (int i = length - 1; i >= 0; --i) { | |
| int count = 0; | |
| if (number[i] >= '1' && number[i] <= '9') { | |
| if (i < length - 1) { | |
| count += counts[i + 1]; | |
| } else { | |
| count += 1; | |
| } | |
| } | |
| if (i < length - 1) { | |
| int digit1 = number[i] - '0'; | |
| int digit2 = number[i + 1] - '0'; | |
| int converted = digit1 * 10 + digit2; | |
| if (converted >= 10 && converted <= 26) { | |
| if (i < length - 2) { | |
| count += counts[i + 2]; | |
| } else { | |
| count += 1; | |
| } | |
| } | |
| } | |
| counts[i] = count; | |
| } | |
| return counts[0]; | |
| } | |
| int main() { | |
| assert(getTransCount("1") == 1); | |
| assert(getTransCount("11") == 2); | |
| assert(getTransCount("100") == 0); | |
| assert(getTransCount("427") == 1); | |
| assert(getTransCount("12258") == 5); | |
| //assert(getTransCount("12258") == 6); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment