记录一下平时用到的算法 语言c/c++
- 将int数组按奇数偶数分开
例如
[1,2,3,4,5,6,7,8,9,10]
排列后
[10,8,6,4,2,1,3,5,7,9]
int * even_odd(int *array,int lenght)
{
int i=0,tmp;
while (lenght--){
if ((array[i])%2==0){
tmp=array[i];
for (int j=i;j>=0;j--){
array[j]=array[j-1];
}
array[0]=tmp;
}
i++;
}
return array;
- c++随机验证码
char * identifying_code(int lenght)
{
int count=0,ch;
char * code=new char[lenght+1]; //手动释放
code[lenght]='\0';
srand((int)time(0));
while (count < lenght){
ch=rand() % 58+65; //产生随机数 65~122
if (ch > 90 && ch < 97) //排除 90~97
continue;
code[count++]=ch;
}
return code;
}
3.反转字符串(小米2016年面试题)
输入
Hello xiao mi
输出
mi xiao Hello
#include <cstring>
#include <iostream>
using namespace std;
void swap(const char *str)
{
int lenght=0,count=0;
char ch=0;
char *Sstr[20];
char tmp[20];
while((ch=*str++)!='\0'){
if (ch==' '){
tmp[lenght]='\0';
Sstr[count]=new char [lenght];
strcpy(Sstr[count++],tmp);
lenght=0;
continue;
}
tmp[lenght]=ch;
lenght++;
}
tmp[lenght]='\0';
Sstr[count]=new char [lenght];
strcpy(Sstr[count],tmp);
for (int i=count;i>=0;i--){
cout<<Sstr[i]<<' ';
}
delete [] Sstr;
}
int main()
{
char *str=new char[10000];
cin.getline(str,10000);
swap(str);
delete [] str;
return 0;
}