题解 | #人民币转换#
人民币转换
http://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <list>
#include <set>
#include <cmath>
#include <cstring>
#include "stdlib.h"
#include <iomanip>
#include <unordered_map>
#include <stack>
#include <sstream>
using namespace std;
vector<string> gewei = { "零","壹","贰","叁","肆","伍","陆","柒","捌","玖" };
vector<string> jinwei = { "仟","佰","拾",""};
bool isTW(string s)
{
int i = 0;
while (i < s.length())
{
if (s[i] != '0')
break;
i++;
}
return (s.length()-i)%4 == 0;
}
bool isNotZ(string s)
{
for (auto c : s)
if (c != '0')
return true;
return false;
}
string read(string num)
{
string res;
if (num.length() >= 9)
{
string qian = read(num.substr(0, num.length() - 8));
if (isTW(num.substr(num.length() - 8, 8)))
{
res = qian + "亿" + read(num.substr(num.length() - 8, 8));
}
else if(num[num.length() - 8] == '0')
res = qian + "亿零" + read(num.substr(num.length() - 8, 8));
else
res = qian + "亿" + read(num.substr(num.length() - 8, 8));
}
else if (num.length() >= 5)
{
string qian = read(num.substr(0, num.length() - 4));
if(num[num.length() - 4] == '0'&& isNotZ(num.substr(num.length() - 4, 4)))
res = qian + "万零" + read(num.substr(num.length() - 4, 4));
else
res = qian + "万" + read(num.substr(num.length() - 4, 4));
}
else
{
if (!isNotZ(num))
return "";
for (int i = 0; i < num.length(); i++)
{
int dig = (4 - num.length() + i);
if (i > 0 && num[i - 1] == '0'&&num[i]=='0')
continue;
if((dig!=2) || (num[i]!='1'))
res = res+gewei[num[i] - '0'];
if(num[i]!='0')
res+= jinwei[dig];
if (i==(num.length()-1)||stoi(num.substr(i + 1, num.length() - i - 1)) == 0)
return res;
}
}
return res;
}
int main()
{
string s;
cin >>s;
string ans;
int k = s.find('.');
string zheng = s.substr(0, k);
string xiao = s.substr(k + 1, 2);
string ans1 = read(zheng);
if (ans1.length() > 0)
ans = "人民币" + ans1 + "元";
else
ans = "人民币";
if (xiao == "00")
ans += "整";
else if (xiao[0] == '0')
ans += gewei[xiao[1] - '0'] + "分";
else if (xiao[1] == '0')
ans += gewei[xiao[0] - '0'] + "角";
else
ans += gewei[xiao[0] - '0'] + "角"+ gewei[xiao[1] - '0'] + "分";
cout << ans;
return 0;
}