华为2013校园招聘上机笔试题-整数转换成字符串

2013华为校园招聘机试题9月10日题

题目来源:http://blog.csdn.net/caollcool/article/category/1234841

解答参考来源:http://www.360doc.com/content/11/1103/19/1317564_161441610.shtml

1:把整数转换成字符串 void ConvertIntToStr(int nVal, char* pStr);

 1 #include<stdio.h>
 2 
 3 void ConvertIntToStr(int nVal, char* pStr)
 4 {
 5     char buf[100];
 6     int temp,i=0,j=0;
 7 
 8     if (nVal == 0)
 9     {
10         *pStr='0';
11         *(pStr+1)='\0';
12         return;
13     }
14     temp = (nVal > 0)?(nVal):(-nVal);
15     //printf("temp:%d\n",temp);
16     while(temp)
17     {
18         buf[i]=temp%10+'0';
19         temp/=10;
20         i++;
21     }
22     //printf("1  here i %d\n",i);
23     if(nVal<0)
24     {
25         buf[i]='-';
26         i++;
27     }
28     //printf("2  here i %d\n",i);
29     buf[i]='\0';
30     pStr[i]='\0';
31     while(buf[j]!='\0')
32     {
33         i--;
34         pStr[i]=buf[j];
35         j++;
36     }
37 }
38 
39 int main()
40 {
41     int a;
42     char str[100];
43     printf("input a number\n");
44     scanf("%d",&a);
45     
46     ConvertIntToStr(a,str);
47     printf(str);
48 
49     return 0;
50 }

注意int类的限制。

函数思路:

首先判断是否为0,然后判断给定的正负,然后将给定数的绝对值以取余的方式逆序保存在buf中,如果给定的是负数,则在buf末尾添加'-'号,并在buf尾部添加'\0'。最后将buf中的字符逆序保存到目标字符串中。

 

posted on 2012-09-18 16:30  Raphael Lou  阅读(320)  评论(0编辑  收藏  举报

导航