Parse Integer

/***
Given any integer, print an English phrase that describes the integer.
eg. One Thousand.
***/

#include<iostream>
#include<map>
#include<stack>
#include <string>

using namespace std;

class phraseInteger {
public:
       phraseInteger(int n);
       ~phraseInteger() {}
       void parseInteger();
       void print();

private:
       int num;
       map<int, string> intmap;
       stack<string> phrase;
};

phraseInteger::phraseInteger(int n) {
       num = n;
       //initial map
       intmap[1] = "One";
       intmap[2] = "Two";
       intmap[3] = "Three";
       intmap[10] = "Ten";
       intmap[20] = "Twenty";
       intmap[30] = "Thirty";
       intmap[100] = "Hundred";
       intmap[1000] = "Thousand";
}

void phraseInteger::parseInteger() {
       int flag = 0;
       int digit;
       while(num != 0) {

              digit = num % 10;
              flag++;
              if(digit != 0) {
                     switch(flag) {
                     case 1:
                                  phrase.push(intmap[digit]);
                                  break;
                     case 2:
                                  phrase.push(intmap[digit*10]);
                                  break;
                     case 3:
                                  phrase.push(intmap[100]);
                                  phrase.push(intmap[digit]);
                                  break;
                     case 4:
                                  phrase.push(intmap[1000]);
                                  phrase.push(intmap[digit]);
                                  break;
                     }     
              }
                    
              num /= 10;
       }

}

void phraseInteger::print() {
       while(!phrase.empty()) {
              cout <<phrase.top()<<" ";
              phrase.pop();
       }
       cout<<endl;
}

void main() {
       phraseInteger myint(1002);
       myint.parseInteger();
       myint.print();

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs