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...Solution:
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;
public int chineseNumberToDecimal(String chineseNumber) { // check the input if(chineseNumber.contains("4")){ throw new IllegalArgumentException("Digit 4 is illegal"); } // convert to nonary number char[] chineseCharArray = chineseNumber.toCharArray(); for (int i = 0; i < chineseCharArray.length; i++) { if (chineseCharArray[i] >= '4' && chineseCharArray[i] <= '9') { chineseCharArray[i]--; } } String nonaryNumber = new String(chineseCharArray); // get the decimal version of the nonary number int decimalNumber = Integer.valueOf(nonaryNumber, 9); return decimalNumber; }
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.
Can you think of the opposite function - decimalToChineseNumber?
So 15->14 according to this code, but should be 13
ReplyDeleteint result= 0;
int power= 1;
for (int i = chineseCharArray.length - 1; i >=0; i--) {
if (chineseCharArray[i] > '4' && chineseCharArray[i] <= '9') {
chineseCharArray[i]--;
}
result += power * chineseCharArray[i];
power *= 9;
}