C程序设计(第二版 新版)第二章 习题

1. 编写函数squeeze(s1,s2)函数,将字符串s1中任何与s2一样的字符删除(2-4)

#include<stdio.h>
#define N 20
void squeeze(char s1[], char s2[])//双层循环,有相同的隔过去,没有相同的通过s1[k++] = s1[i]保留下来
{
     int i, j, k;
     
     for(i = k = 0; s1[i] != '\0'; i++)
     {
           for(j = 0; s2[j] != '\0' && s2[j] != s1[i]; j++)
                 ;
           if(s2[j] == '\0')
                 s1[k++] = s1[i];
     }
     s1[k] = '\0';
}
int main()
{
    char s1[N],s2[N];
    scanf("%s%*c",s1);
    scanf("%s%*c",s2);
    printf("s1 = %s\n",s1);
    printf("s2 = %s\n",s2);
    squeeze(s1,s2);
    printf("s1 = %s\n",s1);
    printf("s2 = %s\n",s2);
    
    getchar();
    return 1;
} 


 2.编写一个函数setbits(x,p,n,y),该函数返回x执行后的结果,将x从第p位置开始的n个二进制位设成y的最右边的n位,x的其余位置保持不变(2-6)

int setbits(int x, int p, int n, int y)
{
     return  x & ~(~(~0 << n) << (p+1-n)) |  (y & ~(~0 << n)) << (p+1-n));    
}


3. 编写函数invert(x,p,n),将x的从p位开始n位求反,其他的位置保持不变(2-7)

int invert(int x, int p, int n)
{
    return x ^ ( ~(~0 << n) << (p+1-n));    
}

 

4.编写函数rightrot(x,n),表示x循环右移n位后的所得的值(2-8  rightrot2是改进做法)

#include<stdio.h>
unsigned int rightrot1(unsigned int x, int n)
{
         int wordlength();
         int rbit;
         
         while( n-- > 0)
         {
                rbit = (x & 1) << (wordlength() - 1);
                x = x >> 1;
                x = x | rbit;
         }
         return x;
}

unsigned int rightrot2(unsigned int x, int n)
{
         int wordlength();
         int rbit;
         if( (n = n % wordlength()) > 0)
         {
             rbit =  ~(~0 << n) & x;
             rbit = rbit << (wordlength() - n);
             x = x >> n;
             x = x | rbit;
         }
         return x;
}

int wordlength()
{
    int i;
    unsigned int v = (unsigned int)~0;
    
    for(i = 1; (v = v >> 1) > 0; i++)
          ;
    return i;
}

int main()
{
    printf("%d\n",wordlength());
    unsigned int s = 12;
    printf("result1 = %u \n",rightrot1(s,2));
    printf("result2 = %u \n",rightrot2(s,2));
    getchar();
    return 1;
} 

 

5.表达式 x &(x -1)可以删除x中最右边数值为1的二进制位置,可以重写bitcount(unsigned int x)函数,加快执行速度(该函数记录x中二进制位为1的个数,bitcount1 和 bitcount2 函数效率对比)

#include<stdio.h>
int bitcount1(unsigned int x)
{
    int i;
    for(i = 0; x != 0; x >>= 1)
    {
          if(x & 01)
               i++;
    }
    return i;
}
int bitcount2(unsigned int x)
{
     int i =0;
     while( x > 0)
     {
            x = x & (x -1);
            i++;
     } 
     return i;
}
int main()
{
    unsigned int x = 14;
    printf("result = %u \n", bitcount1(x));
    printf("result = %u \n", bitcount2(x));
    getchar();
    return 1;
}

你可能感兴趣的:(C程序设计(第二版 新版)第二章 习题)