Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- knakul853
- **/
- class Solution {
- string les_than_20 [20]={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
- string tens [20]= {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
- string thousands[5]={"", "Thousand", "Million", "Billion"};
- public:
- string numberToWords(int num) {
- if(num==0)return "Zero";
- string ans="";
- //x1x2x3x4x5x6x7
- int i=0;
- while(num)
- {
- if(num%1000!=0){
- string temp="";
- f(temp, num % 1000);
- ans = temp + thousands[i] +" "+ ans;
- }
- num/=1000;
- i++;
- }
- i=(int)ans.size()-1;
- while(i >=0 && ans[i]==' ')ans.pop_back(), i--;
- return ans;
- }
- public:
- void f(string &temp, int n)
- {
- cout<<n<<"\n";
- if(n==0)return;
- if(n<20){
- temp += les_than_20[ n ] + " ";
- return;
- }
- if(n<100){
- temp += tens[n/10]+" ";
- f(temp, n %10);
- return;
- }
- temp += les_than_20[n/100]+" Hundred ";
- f(temp, n%100);
- return;
- }
- };
Add Comment
Please, Sign In to add comment