View Code of Problem 16

#include<bits/stdc++.h>
using namespace std;

string numToLetter(char c) {
	switch (c){
	case '1':return "one";
	case '2':return "two";
	case '3':return "three";
	case '4':return "four";
	case '5':return "five";
	case '6':return "six";
	case '7':return "seven";
	case '8':return "eight";
	case '9':return "nine";
	case '0':return "zero";
	}
}

string numToString(int num) {
	string temp = to_string(num);
	string res;
	for (int i = 0; i < temp.length(); i++) {
		res.append(numToLetter(temp.at(i)));
		if (i != temp.length() - 1) {
			res.append(" ");
		}
	}
	return res;
}

int letterToNum(string s) {
	if (s.compare("one")==0) {
		return 1;
	}if (s.compare("two") == 0) {
		return 2;
	}if (s.compare("three") == 0) {
		return 3;
	}if (s.compare("four") == 0) {
		return 4;
	}if (s.compare("five") == 0) {
		return 5;
	}if (s.compare("six") == 0) {
		return 6;
	}if (s.compare("seven") == 0) {
		return 7;
	}if (s.compare("eight") == 0) {
		return 8;
	}if (s.compare("nine") == 0) {
		return 9;
	}if (s.compare("zero") == 0) {
		return 0;
	}
	return -1;
}

int main() {
	int len;
	cin >> len;
	while (len--) {
		int flag;
		string s;
		vector<int>num;
		cin >> flag>>s;
		while (s.compare("=") != 0) {
			char c = s.at(0);
			if (isalpha(c)|| s.compare("+") == 0) {
				num.push_back(letterToNum(s));
			}else {
				num.push_back(stoi(s));
			}
			cin >> s;
		}
		int sum = 0,count = 1;
		for (int i = num.size() - 1; i >= 0; i--) {
			int temp = num[i];
			if (temp != -1) {
				sum += count * num[i];
				count = count * 10;
			}else {
				count = 1;
			}
		}
		if (flag == 0) {
			cout << sum ;
		}else {
			cout << numToString(sum) ;
		}if (len != 0) {
			cout << endl;
		}
	}
	return 0;
}

Double click to view unformatted code.


Back to problem 16