看C程序设计语言这本书时,感觉大神写的程序逻辑性确实很强。很多小细节值得我们学习。
1.转换十六进制。
int hexalpha_to_int(int c)
{
char hexalpha[] = "aAbBcCdDeEfF";
int i;
int answer = 0;
for(i = 0; answer == 0 && hexalpha[i] != '\0'; i++)
{
if(hexalpha[i] == c)
{
answer = 10 + (i / 2);
}
}
return answer;
}
unsigned int htoi(const char s[])
{
unsigned int answer = 0;
int i = 0;
int valid = 1;
int hexit;
if(s[i] == '0')
{
++i;
if(s[i] == 'x' || s[i] == 'X')
{
++i;
}
}
/**
* 这个地方的算法是这样的:
* 0X4567换成16进制要进行这样的运算 4*16^3 + 5*16^2 + 6*16^1 + 7*16^0
* 而这里是这样进行运算的 先记录最高位 answer = 4
* 然后 (((4*16 + 5) * 16) + 6) * 16 + 7
*/
while(valid && s[i] != '\0')
{
answer = answer * 16;
if(s[i] >= '0' && s[i] <= '9')
{
answer = answer + (s[i] - '0');
}
else
{
hexit = hexalpha_to_int(s[i]);
if(hexit == 0)
{
valid = 0;
}
else
{
answer = answer + hexit;
}
}
++i;
}
if(!valid)
{
answer = 0;
}
return answer;
}
2.编写函数any(s1,s2),将字符串s2中的任意字符在s1中第一次出现的位置返回(关键是时间复杂度 O(m + n) 自己写的时候是O(mn)
int any(char *s1, char *s2)
{
char array[256]; /* rjh comments
* (a) by making this char array[256] = {0}; the first loop becomes unnecessary.
* (b) for full ANSIness, #include <limits.h>, make the array unsigned char,
* cast as required, and specify an array size of UCHAR_MAX + 1.
* (c) the return statements' (parentheses) are not required.
*/
int i;
if (s1 == NULL) {
if (s2 == NULL) {
return(0);
} else {
return(-1);
}
}
for(i = 0; i < 256; i++) {
array[i] = 0;
}
while(*s2 != '\0') {
array[*s2] = 1;
s2++;
}
i = 0;
while(s1[i] != '\0') {
if (array[s1[i]] == 1) {
return(i);
}
i++;
}
return(-1);
}
unsigned rightrot(unsigned x, unsigned n)
{
while (n > 0) {
if ((x & 1) == 1)
x = (x >> 1) | ~(~0U >> 1);
else
x = (x >> 1);
n--;
}
return x;
}