在CSDN上看到这个问题, 觉得有点意思就用C#写了这么个算法...
其实不是很复杂, 主要是要处理多种输入的情况.
输出的例子:
12341234
一千二百三十四万一千二百三十四
10001024
一千万一千零二十四
199998001
一亿九千九百九十九万八千零一
其实有的地方念"两"比"二"要舒服, 这个问题...这个算法就没考虑了..
算法代码如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace NumberReader
{
class Program
{
static void Main(string[] args)
{
while (true)
{
string number = Console.ReadLine();
Console.WriteLine(GetChineseString(number));
}
}
private static string GetChineseString(string number)
{
int[] numbers = GetNumberArray(number);
int currentPower = numbers.Length;
int lastNum = 0;
StringBuilder sb = new StringBuilder();
while (currentPower > 0)
{
int currentNum = numbers[numbers.Length - currentPower];
if (currentNum == 0 && lastNum == 0)
{
if (currentPower % 4 == 1)
{
sb.Remove(sb.Length - 1, 1);
sb.Append(GetPowerChar(currentPower));
}
currentPower--;
continue;
}
sb.Append(GetChineseChar(currentNum));
if (currentNum != 0)
{
sb.Append(GetPowerChar(currentPower));
}
lastNum = currentNum;
currentPower--;
}
return sb.ToString();
}
private static string GetPowerChar(int currentPower)
{
int mod = currentPower % 4;
switch (mod)
{
case 0:
return "千";
case 3:
return "百";
case 2:
return "十";
case 1:
int modmod = currentPower % 8;
switch (modmod)
{
case 5:
return "万";
case 1:
if (currentPower != 1)
{
return "亿";
}
break;
}
break;
}
return string.Empty;
}
private static string GetChineseChar(int p)
{
switch (p)
{
case 0:
return "零";
case 1:
return "一";
case 2:
return "二";
case 3:
return "三";
case 4:
return "四";
case 5:
return "五";
case 6:
return "六";
case 7:
return "七";
case 8:
return "八";
case 9:
return "九";
}
return string.Empty;
}
private static int[] GetNumberArray(string number)
{
int[] arr = new int[number.Length];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = (int)number[i] - 48;
}
return arr;
}
}
}