首页 > 代码库 > 常用库函数的编写

常用库函数的编写

1、strcpy

2、strcmp

int strcmp(const char* str1,const char* str2)
{
	assert(str1!=NULL && str2!=NULL);
	while(*str1 && *str2 && *str1 == *str2)
	{
		str1++;
		str2++;
	}
	int res = *str1 - *str2;
	if(res > 0)return 1;
	if(res < 0)return -1;
	return 0;
}

、strcat

、strstr

、strlen

int strlen(const char* str)
{
	assert(str != NULL);
	int len = 0;
	while(*str)
	{
		len++;
		str ++;
	}
	return len;
}

、strncpy

、memset

void* memset(void* src,int c,unsigned int length)
{
	assert(src != NULL);
	char* s = (char*)src;
	while (length --)
	{	
		*s = (char)c;
		s = s + 1;
	}
	return src;
}


、atoi

、itoa

、power

、sqrt

leetcode之sqrt实现

class Solution {
public:
    int sqrt(int x) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        long long a = 0,x2=(long long )x,b = x2,mid=0;
	while(a<=b)
	{
		mid = (a+b)/2;
		long long  temp = mid * mid;
		if(temp == x2 || temp < x2 && (mid+1)*(mid+1)>x2) break;
		else if(temp<x2)a= mid+1;
		else b = mid-1;
	}
	return (int)mid;
    }
};


常用库函数的编写