题目:
题解:
char* singles[] = {"", "One ","Two ","Three ","Four ","Five ","Six ","Seven ","Eight ","Nine "};
char* teens[] = {"Ten ","Eleven ","Twelve ","Thirteen ","Fourteen ","Fifteen ","Sixteen ","Seventeen ","Eighteen ","Nineteen "};
char* tys[] = {"","Ten ","Twenty ","Thirty ","Forty ","Fifty ","Sixty ","Seventy ","Eighty ","Ninety "};char * toEnglish(char* res, int num){ //转英文函数int curNum = num;int hundred = curNum / 100; //百位以上if(hundred != 0){ //是否大于百位strcat(res, singles[hundred]);strcat(res, "Hundred ");}curNum %= 100; //百位以下int ty = curNum / 10; //十位~百位if(ty >= 2){ //是否大于20strcat(res, tys[ty]);curNum %= 10;}if(curNum >= 10){ //10~20strcat(res, teens[curNum-10]);}else if(curNum > 0 && curNum < 10){ //个位strcat(res, singles[curNum]);}return res;
}char * numberToWords(int num){if(num == 0)return "Zero";char* res = (char*)malloc(sizeof(char) * 200); //储存结果res[0] = '\0';int curNum = num;int billion = curNum / 1000000000; //十亿以上if(billion != 0){ //是否大于十亿toEnglish(res, billion); strcat(res, "Billion ");}curNum %= 1000000000; //十亿以下int million = curNum / 1000000; //百万~十亿if(million != 0){ //是否大于百万toEnglish(res, million);strcat(res, "Million ");}curNum %= 1000000; //百万以下int thousand = curNum / 1000; //千~百万if(thousand != 0){ //是否大于千位toEnglish(res, thousand);strcat(res, "Thousand ");}curNum %= 1000; //千位以下toEnglish(res, curNum);int len = strlen(res);res[len-1] = '\0'; //字符串结束return res;
}