Created
April 5, 2020 11:55
-
-
Save adamkorg/4ebe5cdda4f02ea40323208b5aa08abb to your computer and use it in GitHub Desktop.
Leetcode 273: Integer to English Words
This file contains 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
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
string concat(string str, const string& strAdd) { | |
if (!strAdd.empty() && strAdd != "Zero") { | |
str += " "; | |
str += strAdd; | |
} | |
return str; | |
} | |
string numberToWords(int num) { | |
static const vector<string> ones {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; | |
static const vector<string> teens {"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; | |
if (num < 0) return ""; | |
if (num == 0) return "Zero"; | |
if (num<10) return ones[num]; | |
if (num<20) return teens[num-10]; | |
if (num<30) return concat("Twenty",ones[num-20]); | |
if (num<40) return concat("Thirty",ones[num-30]); | |
if (num<50) return concat("Forty",ones[num-40]); | |
if (num<60) return concat("Fifty",ones[num-50]); | |
if (num<70) return concat("Sixty",ones[num-60]); | |
if (num<80) return concat("Seventy",ones[num-70]); | |
if (num<90) return concat("Eighty",ones[num-80]); | |
if (num<100) return concat("Ninety",ones[num-90]); | |
if (num<1000) return ones[num/100]+concat(" Hundred", numberToWords(num-(num/100)*100)); | |
if (num<1000000) return numberToWords(num/1000)+concat(" Thousand",numberToWords(num-(num/1000)*1000)); | |
if (num<1000000000) return numberToWords(num/1000000)+concat(" Million",numberToWords(num-(num/1000000)*1000000)); | |
return numberToWords(num/1000000000)+concat(" Billion",numberToWords(num-(num/1000000000)*1000000000)); | |
} | |
int main() { | |
cout << numberToWords(1234567891) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment