算法学习之基础题
基础题之字符串
题目:
把手放在键盘上,稍不注意就会往右错一位。Q会变成W,J会变成K。
输入一个错位后敲出的字符串,输出打字员本来想打出的句子。
分析:如何进行这样的变换呢?一种方法是使用if语句或者switch语句,如if(c==‘W’)putchar(‘Q’)。
但很明显,这样做太麻烦。一个较好的方法是使用常量数组。
题目:
TeX括号
在TeX中,左双引号是“,右双引号是”,输入一篇包含双引号的文章,你的任务是把它转换成TeX的格式。
样例输入:
"To be or not to be,"quoth the Bard,"that is the question".
样例输出:
“To be or not to be,”quoth the Bard,“that is the question”.
分析:本题的关键是,如何判断一个双引号是“左”双引号还是“右”双引号。
#include <conio.h>
#include<stdio.h>
#include<string.h>
int main(){
int c,q=1;
while((c=getchar())!=EOF){//如果结束,将获取的字符串逐步执行下面的if语句块
if(c== '"'){
printf("%s","test");
printf("%s",q?"“":"”");
q = !q;
}else{
printf("%c",c);
}
}
getch();
return 0;
}
周期串问题
题目:
如果一个字符串可以由某个长度为k的字符串重复多次得到,我们说该串以k为周期。
例如,abcabcabc以3为周期。输入一个长度不超过80的串,输出它的最小周期。
样例输入:HoHoHo
样例输出:2
#include <conio.h>
#include<stdio.h>
#include<string.h>
int main(){
char word[100];
scanf("%s",word);//获取字符串
int len = strlen(word);//获取字符串长度
for(int i=1;i<=len;i++){
if(len % i==0){//获取整除的最小长度i
int ok = 1;
for(int j = i;j<len;j++){
if(word[j]!=word[j%i]){//验证之后的单词是否相同
ok = 0;
break;
}
}
if(ok){
printf("%d\n",i);
break;
}
}
}
getch();
return 0;
}
高精度运算
题目:小学生算术
任务,计算两个整数在相加时需要多少次进位。
样例输入:
123 456
555 555
123 594
0 0
样例输出:
0
3
1
#include <conio.h>
#include<stdio.h>
#include<string.h>
int main(){
int a,b;
while(scanf("%d%d",&a,&b)==2){//输入两个值,进行一次块处理
if(!a&&!b)return 0;//判断退出
int c = 0,ans = 0;
for(int i = 9;i>=0;i--){
c = (a%10+b%10+c)>9?1:0;
ans += c;
a /= 10;
b /= 10;
}
printf("%d\n",ans);
}
getch();
return 0;
}