水仙花数

xiaoxiao2021-02-28  69

水仙花数

时间限制: 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(代替的位置,代替的长度,代替的字符串)

转载请注明原文地址: https://www.6miu.com/read-31508.html

最新回复(0)