免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 7692 | 回复: 10
打印 上一主题 下一主题

添一道思科笔试题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-01-15 00:57 |只看该作者 |倒序浏览
编一函数 invert(int x, int p, int n) 使得整数x从第p位开始的n位反转。
最右边的位为第0位。不可以用循环!
比如x=1010011010001, p=4, n=4,运行函数之后
      x=1010000100001

论坛徽章:
0
2 [报告]
发表于 2006-01-15 01:04 |只看该作者
反转?没看懂题目

论坛徽章:
0
3 [报告]
发表于 2006-01-15 10:53 |只看该作者
too easy!

论坛徽章:
0
4 [报告]
发表于 2006-01-15 19:41 |只看该作者

回复 2楼 dong_yoyo 的帖子

反转就是:0变1,1变0。

还请大虾指教!不要用循环哦!

[ 本帖最后由 sorock 于 2006-1-15 19:46 编辑 ]

论坛徽章:
0
5 [报告]
发表于 2006-01-15 20:39 |只看该作者
Maybe I am too fool,I think it isnot easy,it took me much time.

  1. void main()
  2. {
  3.         unsigned int iDisp=0x14C1;
  4.         short       int  p=4,n=4;

  5.         printf("%0B\n",iDisp);     
  6.         
  7.         /*Maybe some complier hasnot the B option of  printf, then you can print it a decimal.*/

  8.         iDisp = iDisp ^( (1<<(p+n)) -(1<<p) );

  9.         printf("%0B\n",iDisp);
  10. }
复制代码

[ 本帖最后由 zhhui2000 于 2006-1-15 22:11 编辑 ]

论坛徽章:
0
6 [报告]
发表于 2006-01-15 20:40 |只看该作者
异或

论坛徽章:
0
7 [报告]
发表于 2006-01-15 21:15 |只看该作者
家里没gcc,我是用的TC编的,int 是16位。
位操作类型最好是unsigned
#include<stdio.h>
#include<string.h>

#define INT_LENGTH sizeof(int)*8
int invert(unsigned int x, int p, int n);
int main()
{
    printf("%x\n", invert(0x0f00, 4, 12));
    getch();
    exit(0);
}
int invert(unsigned int x, int p, int n)
{
    unsigned int temp = x;
    int left = INT_LENGTH - p - n;
    int right = p;

    temp <<= left;
    temp >>= left+right;
    temp <<= right;
    x -= temp;

    temp = ~temp;
    temp <<= left;
    temp >>= left+right;
    temp <<= right;
    x += temp;

    return x;
}

论坛徽章:
0
8 [报告]
发表于 2006-01-15 22:09 |只看该作者
原帖由 zhhui2000 于 2006-1-15 20:39 发表
Maybe I am too fool,I think it isnot easy,it took me much time.

[code]void main()
{
        unsigned int iDisp=0x14C1;

        printf("%0B\n",iDisp);     
        
        /*May ...


呵呵,强人啊....................学习中.....................

论坛徽章:
0
9 [报告]
发表于 2006-01-16 01:33 |只看该作者
# include<iostream>
using namespace std;

int invert(int a,int p,int n)
{
        int nn=(1<<n)-1;
    int pp=nn<<p;
    int result=a^pp;
        return result;
}

int main()
{
        int a,p,n,t;
        cin>>a>>p>>n;
        t=invert(a,p,n);
        cout<<t;
        return 0;
}

论坛徽章:
0
10 [报告]
发表于 2006-01-16 11:18 |只看该作者

回复 5楼 zhhui2000 的帖子

The first solution, the best solution!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP