3.1.4. Questions

3.1.4.1. Chinese Number System

Number ‘4’ is considered an unlucky number in China because it is nearly homophonous to the word “death(死)”. For this reason, there is a new number system similar to the decimal system but has no ‘4’. For example: 1,2,3,5,6,7…13,15…23,25…33,35…39,50…

Here 5 is 4 in decimal system, and 15 is 13…

Write a function which takes as an input a positive number (Chinese number) and provides an output number (decimal number or error):

1 -> 1; 2 -> 2; 5 -> 4; 4 -> illegal; 15 -> 13;

The whole idea is based on that a Chinese number is a number in the nonary system and its digits are: 0, 1, 2, 3, 5, 6, 7, 8, 9. The ordinary nonary system has the digits: 0, 1, 2, 3, 4, 5, 6, 7, 8. Therefore we can convert the given Chinese number into an ordinary number in the nonary system. Then it is easy to get the decimal number having an ordinary nonary number.

 1string chinese_to_decimal(string s){
 2    if(s.find('4')!=string::npos)
 3        return "illegal";
 4
 5    // 1. map from chinese to nonary number system
 6    map<char,char> m={{'5','4'},{'6','5'},{'7','6'},{'8','7'},{'9','8'}};
 7    string r;
 8    for(char c: s)
 9        r += m.count(c)?m[c]:c;
10
11    // 2. from nonary to decimal
12    int t=stoi(r), w=1, n=0, BASE=9;
13    while(t)
14        n += (t%10)*w, w*=BASE, t/=10;
15    return to_string(n);
16}

Actually, line number 11 to 14 can be replaced by: stoi(r,0, 9) because function stoi can convert string to decimal integer from non-decimal number.