题解 | #阿拉伯数字转中文#
阿拉伯数字转中文
https://www.nowcoder.com/practice/6eec992558164276a51d86d71678b300
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return string字符串
*/
string A[10] = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
string B[4] = {"", "十", "百", "千"};
string C[4] = {"", "万", "亿", "万亿"};
vector<string> tmp;
string ans = "";
void fun2(int part, string ans) {
bool lastZero = true;
int pos = 0;
while (part > 0) {
int now = part % 10;
part /= 10;
if (now == 0) {
if (!lastZero) {
tmp.push_back(A[0]);
lastZero = true;
}
} else {
lastZero = false;
tmp.push_back(B[pos]);
tmp.push_back(A[now]);
}
pos++;
}
}
string fun(int num) {
if(num == 0)
return A[0];
int pos = 0;
string ans = "";
bool last = false;
while (num > 0) {
int part = num % 10000;
num /= 10000;
if (last) {
tmp.push_back(A[0]);
last = false;
}
if (part > 0 && part < 1000)
last = true;
if(part > 0)
tmp.push_back(C[pos]);
fun2(part, ans);
pos++;
}
int n = tmp.size() - 1;
if(n - 1 >= 0 && tmp[n - 1] == "十" && tmp[n] == "一")
n--;
for(int i = n; i >= 0; i--)
ans += tmp[i];
return ans;
}
string num2cn(int n) {
// write code here
if(n < 0) {
ans = "负";
n = -n;
}
ans += fun(n);
return ans;
}
};

