浙江大学PAT_乙级_1002. 写出这个数 (20)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pythontojava/article/details/45441835

题目链接:点这里

读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。

输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10100

输出格式:在一行内输出n的各位数字之和的每一位,拼音数字间有1 空格,但一行中最后一个拼音数字后没有空格。

输入样例:
1234567890987654321123456789
输出样例:
yi san wu
我的c++程序:
<pre name="code" class="cpp">#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
	string s;
	string spell[10] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
	stack<int> st;
	int num=0,i=0,flag=1;//num数字之和,i控制循环,flag控制有无空格
	cin >> s;
	for (i=0; i < s.size(); i++)
	{
		num = num + s[i] - 48;
	}
	while (num != 0)
	{
		st.push(num %10);//将最低位数字入栈
		num = num / 10;
	}
	if (st.empty())//num==0时,栈为空
	{
		cout << 0;
	}
	while (!st.empty())
	{
		if (flag == 1)
		{
			cout <<spell[st.top()];
			flag = 0;
		}
		else
		{
			cout << ' ' << spell[st.top()];
		}
		st.pop();//出栈
	}
	//system("pause");
	return 0;
}



========分割线========

2015年6月11日补充python实现

spell=["ling","yi","er","san","si","wu","liu","qi","ba","jiu"]
s=raw_input()
sum=int(0)
for i in s:
	sum=int(i)+sum
result=[]
while sum!=0:
	result.append(sum%10)
	sum=sum/10
result.reverse()
for i in result:
	print spell[i],


===========

2015.7.12

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s;
	string spell[10] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
	int st[10] = { 0 }, length = 0;//length数字之和的位数
	int num = 0, i = 0;//num数字之和,i控制循环
	cin >> s;
	for (i = 0; i < s.size(); i++)
	{
		num = num + s[i] - 48;
		length++;
	}
	i = 0;
	while (num != 0)
	{
		st[i]=(num % 10);//将最低位数字入数组
		num = num / 10;
		i++;
	}
	length = (i - 1);
	for (i =length; i>0; i--)
	{
		cout << spell[st[i]]<<' ';
	}
	cout << spell[st[0]];//最后一位没有空格
	//system("pause");
	return 0;
}

=====

2015.7.17

JAVA

import java.util.*;//输入
import static java.lang.System.*;//输出
public class Main
{
	public int count(String str)//计算各位数之和的方法
	{
		int sum=0;
		for(int i=0;i<str.length();i++)
		{
			sum=sum+str.charAt(i)-48;
		}
		return sum;
	}
	public static void main(String[] args)
	{
		Scanner cin=new Scanner(System.in);
		String str=cin.nextLine();
		String spell[]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
		Main M=new Main();
		str=M.count(str)+"";//把各位数之和转换为字符串
		for(int i=0;i<str.length()-1;i++)
		{
			out.print(spell[str.charAt(i)-48]+' ');//str.charAt(i)-48]把字符串第i位字符转换为int
		}
		out.print(spell[str.charAt(str.length()-1)-48]);//输出最后一位
	}
}



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页