华为2道机试题(review)

华为2道机试题:

/** @date:2010/09/14 @author:weedge @comment: 1. 识别字符串中的整数并转换为数字形式 问题描述: 识别输入字符串中所有的整数,统计整数个数并将这些字符串形式的整数转换为数字形式整数。 要求实现函数: void take_num(const char *strIn, int *n, unsigned int *outArray) 【输入】 strIn: 输入的字符串 【输出】 n: 统计识别出来的整数个数 outArray:识别出来的整数值,其中outArray[0]是输入字符串中从左到右第一个整数, outArray[1]是第二个整数,以此类推。数组地址已经分配,可以直接使用 【返回】 无 注: I、 不考虑字符串中出现的正负号(+, -),即所有转换结果为非负整数(包括0和正整数) II、 不考虑转换后整数超出范围情况,即测试用例中可能出现的最大整数不会超过unsigned int可处理的范围 III、 需要考虑 0 开始的数字字符串情况,比如 "00035" ,应转换为整数35; "000" 应转换为整数0;"00.0035" 应转换为整数0和35(忽略小数点:mmm.nnn当成两个数mmm和nnn来识别) IV、 输入字符串不会超过100 Bytes,请不用考虑超长字符串的情况。 示例 输入:strIn = "ab00cd+123fght456-25 3.005fgh" 输出:n = 6 outArray = {0, 123, 456, 25, 3, 5} */ #include <stdio.h> #include <stdlib.h> #include <string.h> void take_num(const char *strIn, int *n, unsigned int *outArray){ if(strIn == NULL){ printf("this is null string."); }else{ int i = 0; int j = 0; int len = strlen(strIn); while(j<=len){ if(*strIn >= 0 && *strIn <=9){ const char *begstr = strIn; const char *endstr = strIn; while(*strIn >= 0 && *strIn <=9){ if(*strIn == 0){ begstr = strIn; } endstr = strIn; strIn++; } if(*endstr != 0){ /* *(++endstr) = /0; */ outArray[i] = atoi(begstr);/*atoi() just read back the front number*/ i++; }else{ outArray[i] = 0; i++; } } strIn++; j++; } *n = i; } } int main(){ char *strIn = "ab00cd+123fght456-25 3.005fgh"; int n=0; unsigned int outArray[20]; take_num(strIn,&n,outArray); printf("n:%d/n",n); for(int i=0; i<n; i++){ printf("outArray[%d]=%u/n",i,outArray[i]); } system("pause"); return 0; }

review:

/**
@date:2011/09/02 review (not to use the fun atoi())
@author:weedge
*/
#include <stdio.h>
#include <stdlib.h>

void take_num(const char *strIn, int *n, unsigned int *outArray){
	if(strIn == NULL){
		printf("this is null string.");
	}else{
		int i = 0;
		while(*strIn){
			if(*strIn >= 0 && *strIn <=9){
				outArray[i] = 0;
				while(*strIn >= 0 && *strIn <=9){
					outArray[i] = outArray[i]*10 + ((*strIn++) - 0);
				}		
				i++;
			}
			strIn++;
		}
		*n = i;
	}
}

void take_num1(const char *strIn, int *n, unsigned int *outArray){ //use atoi()
	if(strIn == NULL){ 
		printf("this is null string."); 
	}else{ 
		int i = 0; 
		while(*strIn){ 
			if(*strIn >= 0 && *strIn <=9){ 
				const char *begstr = strIn; 
				while(*strIn >= 0 && *strIn <=9){ 
					strIn++; 
				} 
				outArray[i] = atoi(begstr);/*atoi() just read back the front number*/ 
				i++; 
			} 
			strIn++;
		} 
		*n = i; 
	} 
} 

int main(){
	char *strIn = "ab00cd+123000fght456-25  3.005fgh";
	int n=0;
	unsigned int outArray[20];
	take_num1(strIn,&n,outArray);
	printf("n:%d/n",n);
	for(int i=0; i<n; i++){
		printf("outArray[%d]=%u/n",i,outArray[i]);
	}
	system("pause");
	return 0;
}


经验分享 程序员 微信小程序 职场和发展