華為機試題(9)--將兩個數從字串轉為數,將這兩個數做乘積後再轉化為字串儲存起來

pengfoo發表於2012-04-12

求兩個字串的乘積,結果存到字串中,例如字串一中存的“657891”,字串二中存的“521”,分別將字串中的字元轉換成整型數字,進行計算後,再轉換成字元型別儲存起來

 

#include<stdio.h> 
#include <stdlib.h>

void mul(char *input1,int n1,char *input2, int n2,char *output)
{
	char *p1=input1;
	char *p2=input2;
	int res1,res2,res;
	char tmp[50];
	int m=0,i;
	if(p1 == NULL || p2 == NULL)
		return;

	res1 = *p1-'0';
	while( *++p1)
		res1 = 10*res1+(*p1-'0');
	printf("res1=%d\n",res1);

	res2 = *p2 - '0';
	while( *++p2)
		res2 = 10*res2+(*p2-'0');
	printf("res2=%d\n",res2);

	res = res1*res2;

	while(res > 0)
	{
		tmp[m] = res % 10+ '0';
		res = res/10;
		m++;
	}
	tmp[m] = '\0';

	for(i=0;i<m;i++)
		output[i] = tmp[m-1-i];
	output[m]='\0';
}


int main()
{
	char input1[50]="19";
	char input2[50]="19";
	char output[50];
	mul(input1,strlen(input1),input2,strlen(input2),output);
	printf("mul result=%s\n",output);
	system("pause");
	return 0;
}


相關文章