前段时间做的部分笔试题和答案(提醒自己)
编写一函数实现数组的递归求和
#include
<
stdio.h
>
#include
"
config.h
"


int
sum(
int
A[], size_t n)
{
if (1 == n)
{
return 1;
}
else
{
return sum(&A[n-1], n-1) + n;
}
}


int
main(
void
)
{
int A[] = { 1, 2, 3, 5, 9, 1};
printf("%d/n", sum(A, ARRAY_LENGTH(A)));
return 0;
}
#ifndef CONFIG_H
#define
CONFIG_H


#define
ARRAY_LENGTH(x) sizeof(x)/sizeof(x[0])


#endif
编写一函数实现str到long的转换
#include
<
stdio.h
>
#include
<
string
.h
>
#include
<
assert.h
>



long
str2long(
const
char
*
str)
{
long result = 0;
while ('/0' != *str)
{
result = result * 10 + (*str - '0');
++str;
}
return result;
}




int
main(
void
)
{
char *str = "1234";
printf("/n%d/n", str2long(str));
return 0;
}
上面的代码没有考虑负数^_^
实现strcpy函数
char
*
mystrcpy(
char
*
dst,
const
char
*
src)
{
assert(NULL != dst && NULL != src);
while (*dst++ = *src++);
return dst;
}


int
main(
void
)
{
char *dst[20];
char *src = "test";
mystrcpy(dst, src);
puts(dst);
return 0;
}
判断一个整数是否是回文
long
symm(
long
n)
{
long i, m;
m = 0;
i = n;
while (i)
{
m = m * 10 + i % 10;
i /= 10;
}
return (n == m ? 1:0);
}
实现Insertion sort
#include
<
stdio.h
>
#include
<
string
.h
>

typedef
int
ElemType;
void
InsertionSort(ElemType A[], size_t n)
{
int i;
int pass;
ElemType tmp;
for (pass = 1; pass < n; pass++)
{
tmp = A[pass];
for ( i = pass; i > 0 && A[i-1] > tmp; i--)
{
A[i] = A[i-1];
}
A[i] = tmp;
}
}

int
main(
void
)
{
int i;
ElemType A[] = {1, 2, 4, 8, 6, 98, 11, 25, 44, 35};
puts("Before sort:");
for(i = 0; i< sizeof(A)/sizeof(ElemType); i++)
{
printf("%d ", A[i]);
}
printf("/n");
InsertionSort(A, sizeof(A)/sizeof(ElemType));
puts("After sort:");
for(i = 0; i< sizeof(A)/sizeof(ElemType); i++)
{
printf("%d ", A[i]);
}
printf("/n");
return 0;
}
本文提供了一系列常见算法题目的解决方案,包括递归数组求和、字符串转换为数值、字符串复制、判断回文数以及插入排序算法的实现。这些题目有助于巩固基本的数据结构与算法知识。


2364

被折叠的 条评论
为什么被折叠?



