研究一种将采用整数 (num) 和整数 (n) 的方法,该整数 (n) 将采用 n 位数字的绝对值。我相信我的逻辑是正确的,已经在纸上完成了它并且成功了,但是代码似乎已经关闭了。非常感谢所有帮助!
/**
* Take the absolute value of an n-bit number.
*
* Examples:
* abs(0x00001234, 16); // => 0x00001234
* abs(0x00001234, 13); // => 0x00000DCC
*
* Note: values passed in will only range from 1 to 31 for n.
*
* @param num An n-bit 2's complement number.
* @param n The bit length of the number.
* @return The n-bit absolute value of num.
*/
public static int abs(int num, int n)
{
int shifter = num << (n+1);
int newInt = num & ~shifter;
return newInt;
}