微软一道笔试题:怎样只用4行代码编写出一个从字符串到长整形的转换函数?
#include <stdlib.h>
#include <stdio.h>
// 判断是否为数字
#define MY_ISDIGIT(a) ( (a)>='0' && (a)<='9')
long my_atol(const char *a)
{
// 1. 初始化
long l = 0;
// 2. 判断正负
char sign = ( MY_ISDIGIT(*a) ) ? '+' : (*a!='+' && *a!='-') ? 0 : *a++;
// 3. 循环
while ( MY_ISDIGIT(*a) ) l = l*10 + ((*a++)&'/x0F');
// 4. 根据符号返回结果
return (sign=='+') ? l : -l;
}
void main(void)
{
char str[] = "-123456789a";
long l1 = atol(str);
long l2 = my_atol(str);
printf("l1 = %ld, l2 = %ld", l1, l2);
return;
}
2005年华为招聘--C语言笔试试题
一、判断题(对的写T,错的写F并说明原因,每小题4分,共20分)
1、有数组定义int a[2][2]={{1},{2,3}};则a[0][1]的值为0。( T )
2、int (*ptr) (),则ptr是一维数组的名字。( F )
3、指针在任何情况下都可进行>,<,>=,<=,==运算。( ? )
4、switch(c) 语句中c可以是int ,long,char ,float ,unsigned int 类型。( F )
5、#define print(x) printf("the no, "#x",is ") ( T )
二、填空题(共30分)
1、在windows下,写出运行结果,每空2分,共10分。
char str[ ]= "Hello";
char *p=str;
int n=10;
sizeof(str)=( 6 )
sizeof(p)=( 4 )
sizeof(n)=( 4 )
void func(char str[100])
{ }
sizeof(str)=( 4 )
2、
void getmemory(char **p, int num)
{
*p=(char *) malloc(num);
}
void test(void)
{
char *str=NULL;
getmemory(&str,100);
strcpy(str,"hello");
printf(str);
}
运行test函数有什么结果?( hello 但内存泄漏 )10分
3、设
int arr[]={6,7,8,9,10};
int *ptr=arr;
*(ptr++)+=123;
printf("%d,%d", *ptr, *(++ptr));
( 8,8 ) 10分
二、编程题(第一小题20,第二小题30分)
1、 不使用库函数,编写函数int strcmp(char *source, char *dest)
相等返回0,不等返回-1;
int my_strcmp(char *source, char *dest)
{
if (source == NULL || dest == NULL) return -1;
while( (*source) == (*dest++) )
if ((*source++)=='/0') return 0;
return -1;
}
2、 写一函数int fun(char *p)判断一字符串是否为回文,是返回1,不是返回0,出错返回-1
int palindrome(char *p)
{
char * e;
if (p == NULL) return -1;
e = p + strlen(p) - 1;
while( *p++ == *e-- )
if (p>=e) return 1;
return 0;
}