水仙花数

水仙花数

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 0
描述
请判断一个数是不是水仙花数。
其中水仙花数定义各个位数立方和等于它本身的三位数。
输入
有多组测试数据,每组测试数据以包含一个整数n(100<=n<1000)
输入0表示程序输入结束。
输出
如果n是水仙花数就输出Yes
否则输出No
样例输入
153
154
0
样例输出
Yes
No
来源
C语言课本习题改编
上传者

张云聪


原题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=39


问题分析:找到对应的字符串,然后进行替换。

不用c++中string类代码:

#include <iostream>
#include <stdio.h> 
#include <string.h>
#include <math.h>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <algorithm>
#define MAX 1000 
using namespace std; 

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	char input[MAX];
	while(gets(input)){
		char output[MAX];
		int size=0;
		int length=strlen(input);
		for(int i=0;i<length;i++){
			if(input[i] == 'y' && input[i+1] == 'o' && input[i+2] == 'u'){
				output[size++]='w';
				output[size++]='e';
				i=i+2;
			} else
			{
				output[size++] = input[i];
			}
		}
		for(int i=0;i<size;i++){
			cout<<output[i];
		}
		cout<<endl;
	}
	return 0;
}
优秀代码:

01. #include<algorithm>
02. #include<iostream>
03. #include<string>
04.  
05. using namespace std;
06.  
07. int main()
08. {
09. string s, s1, s2;
10. while(getline(cin,s))
11. {
12. int flag;
13. s1 = "you";
14. s2 = "we";
15. flag = s.find(s1,0);
16. while(flag != string::npos)
17. {
18. s.replace(flag, 3, s2);
19. flag = s.find(s1, flag + 1);
20. }
21. cout << s << endl;
22. }
23. return 0;
24. }

代码分析:

不用c++中string类是因为想用c语言来实现主要逻辑,但c中string.h库中的函数不是很清楚,所以就自己写了查找的函数。自己的代码中其实不需要遍历到length-1,you是3个字符,因此遍历到length-3即可结束遍历.优秀代码主要用了string中的两个函数:find()和replace()。

find(要查找的字符串,查找开始位置);

replace(代替的位置,代替的长度,代替的字符串)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值