1:折半查找
int binsearch(int x,int v[],int n)
{
int low,high,mid;
low = 0;
high = n -1;
mid = (low + high)/2;
while(low <= high && x != v[mid]){
if(x > v[mid]){
low = mid +1;
}else{
high = mid -1;
}
mid = (lov + high)/2;
}
if(x == v[mid]){
return mid;
}else
return -1;
}
2:编写atoi()函数
int myatoi(char s[])
{
int i,sig = 1,n;
for(i = 0;isspace(s[i]);i ++)
;
sig = (s[i] == '-') ? -1 :1;
if(s[i] == '+' || s[i] == '-')
i ++;
for(n = 0;isdigit(s[i]);i ++){
n = n * 10 + (s[i] - '0') ;
}
return sig * n;
}
3:编写itoa()功能函数(另一种方法:用栈)
#include
#define MAXLEN 32
void itoa(int num,char s[]);
void reverse(char s[]); //翻转字符串
int main(void)
{
int i = 98762;
char s[MAXLEN];
itoa(i,s);
printf("%s",s);
return 0;
}
void itoa(int num,char s[])
{
int i,sig;
if(num < 0)
sig = num;
i = 0;
do{
s[i++] = abs(num % 10) + '0';
}while((num = num / 10) != 0);
if(sig < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/*
将逆序的字符串进行翻转
*/
void reverse(char s[])
{
int i = 0;
while(s[i] != '\0'){
i ++;
}
i --;
int low = 0;
char tmp;
while(low <= i){
tmp = s[low];
s[low] = s[i];
s[i] = tmp;
low ++; i --;
}
}
阅读(1287) | 评论(0) | 转发(0) |