劍指offer--細節(17、38、44)

offer17

輸入一個表示整數的字符串,把該字符串轉換成整數並輸出。例如輸入字符串"345",則輸出整數345

需要考慮到爲負數,字符串中出現其他的非數字字符,數值溢出等情況。


bool str_to_int(const char *a,int &n){
	if(a==NULL){
		printf("error,input is empty!\n");
		return false;
	}
	char sign=0;
	int len=strlen(a);
	int i=0;
	long long num=0;
	//這裏需要注意,最小負數的絕對值比最大正數要大1,所以需要用longlong保存。
	long long lim=INT_MAX;
	lim++;
	if(*a=='+'||*a=='-'){
		sign=*a;
		i++;
	}

	for(;i<len;i++)
	{
		//檢查是否是數字字符
		if(!(a[i]>='0'||a[i]<='9')){
			printf("error,input is not int!\n");
			return false;
		}
		num=num*10+(int)(a[i]-'0');
		if(num>lim){
			printf("error,input is too big!\n");
			num=0;
			return false;
		}
	}

	if(sign=='-')
		num=-num;
	//如果超出範圍,主要是考慮到最小負數的絕對值,
	if(num<INT_MIN||num>INT_MAX){
		printf("error,input is too big!\n");
		num=0;
		return false;
	}

	n=num;
	return true;
}

offer38

輸入數字n,按順序輸出從1最大的n10進制數。比如輸入3,則輸出123一直到最大的3位數即999

這時候需要考慮n很大時,需要用字符串來保存數值,要模擬加1的操作。


void AddOne(char *a)
{
	int len=strlen(a);
	len--;
	int sign=0;
	sign=((a[len]-'0')+1)/10;
	a[len]=((a[len]-'0')+1)%10+'0';
	
	while (sign)
	{
		len--;
		sign=((a[len]-'0')+1)/10;
		a[len]=((a[len]-'0')+1)%10+'0';
	}
}

void Print(char *a)
{
	int n=strlen(a);
	int i;
	for (i=0;i<n;i++)
	{
		if (a[i]!='0')
			break;
	}
	printf("%s \n",a+i);
}

void PrintNum(int n)
{
	char *a=(char*)malloc(sizeof(char)*(n+2));
	memset(a,'0',n+1);
	a[n+1]='\0';
	printf("%s \n",a);
	AddOne(a);
	Print(a);
	while (a[0]=='0')
	{
		Print(a);
		AddOne(a);
	}
}

offer44

實現函數double Power(double base, int exponent),求baseexponent次方。不需要考慮溢出。

在最笨的算法能夠實現時,我們需要對其進行優化,

首先要考慮錯誤的情況,o的負次方是不存在的,這裏規定了函數原型,無法用返回值來判定輸入的合法性,可以考慮用全局變量標誌。可以考慮用遞歸區分次方的奇偶。就可以了

bool InvalidInput=false;

double PowerNoNegtive(double base, int exponent)
{
	if (base==0)
		return 0.0;
	if (exponent==1)
		return base;
	if (exponent==0)
		return 1;
	if (exponent%2)
	{
		double temp=PowerNoNegtive(base,(exponent-1)/2);
		return temp*temp*base;
	}
	else
	{
		double temp=PowerNoNegtive(base,exponent/2);
		return temp*temp;
	}
	
}


double Power(double base, int exponent)
{
	if (base==0&&exponent<0)
	{
		InvalidInput=true;
		return 0.0;
	}
	if (exponent<0)
	{
		return 1.0/PowerNoNegtive(base,-exponent);
	}
	else
		return PowerNoNegtive(base,exponent);

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章