目录
题目一:Fibonacci数列
具体要求如下:
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int n = 0;
scanf("%d", &n);
int a = 0;//第一个
int b = 1;//第二个
int c = 0;
while (1)
{
if (n == b)
{
printf("0\n");
break;
}
else if (n < b)
{
printf("%d\n", (n - a) > (b - n) ? b - n : n - a);
break;
}
c=a + b;
a = b;
b = c;
}
return 0;
}
看完代码,如果还不理解的话,看图:
题目二:替换空格
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str,int length) {
//str是要修改的字符串
//length是要修改的字符串的长度
char* cur=str;
int count=0;
while(*cur)
{
if(*cur==' ')
{
count++;
}
cur++;
}
int end1=length-1;
int end2=length+2*count-1;
while(end1!=end2)
{
if(str[end1]!=' ')
{
str[end2]=str[end1];
end1--;
end2--;
}
else
{
str[end2--]='0';
str[end2--]='2';
str[end2--]='%';
end1--;
}
}
}
};
补充:
先将数组遍历一遍,找出有多少个空格,以便于后面需要多长的位置
没有空格时,end1 和end2同时走一步,将end1位置的数据,拷给end2位置
遇到空格,end1走一步,跳过空格,end2走三步,放入%20