我正在尝试实现一个旋转左侧函数,它将整数x向左旋转n位
到目前为止我有这个:
int rotateLeft(int x, int n) {
return ((x << n) | (x >> (32 - n)));
}
Run Code Online (Sandbox Code Playgroud)
我已经意识到不能为签名整数工作..任何人都有任何想法如何解决这个问题?
所以现在我试过了:
int rotateLeft(int x, int n) {
return ((x << n) | ((x >> (32 + (~n + 1))) & 0x0f));
}
Run Code Online (Sandbox Code Playgroud)
并收到错误:
错误:测试rotateLeft(-2147483648 [0x80000000],1 [0x1])失败...... ...给出15 [0xf].应为1 [0x1]
我有一个调用的函数replaceByte(x,n,c)是替换字节n在x与c具有以下限制:
replaceByte(0x12345678,1,0xab) = 0x1234ab78! ~ & ^ | + << >>Max ops:10
int replaceByte(int x, int n, int c) {
int shift = (c << (8 * n));
int mask = 0xff << shift;
return (mask & x) | shift;
}
Run Code Online (Sandbox Code Playgroud)但是当我测试它时,我得到了这个错误:
错误:测试replaceByte(-2147483648 [0x80000000],0 [0x0],0 [0x0])失败...... ...给出0 [0x0].应该是-2147483648 [0x80000000]
在意识到*不是合法的操作员后,我终于弄明白了......如果你好奇,这就是我所做的:
int replaceByte(int x, int n, int c) { …Run Code Online (Sandbox Code Playgroud) 这是问题,我现在有什么问题,我只是不明白它是怎么回事......
getByte - 从字x中提取字节n从0(LSB)到3(MSB)编号的字节示例:getByte(0x12345678,1)= 0x56法律操作:!〜&^ | + << >> Max ops:6评级:2
int getByte(int x, int n) {
return ((x << (24 - 8 * n)) >> (8 * n));
}
Run Code Online (Sandbox Code Playgroud) c ×3