การทำแบบฝึกหัดจากระบบคอมพิวเตอร์: มุมมองของโปรแกรมเมอร์ และนี่คือสิ่งที่ผมคิดขึ้นมา น่าเสียดายที่สิ่งนี้ใช้ไม่ได้ในกรณีที่ n=32 หาก n=32 มันไม่เปลี่ยน x เลย ดังนั้นมันจึงคืนค่า 1 โดยไม่คำนึงถึง นี่เป็นปัญหาหาก x=0x80000000 เพราะในกรณีนี้ควรคืนค่า 0
/*
* fitsBits - return 1 if x can be represented as an
* n-bit, two's complement integer.
* 1 <= n <= 32
* Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int fitsBits(int x, int n) {
int diff = 32 +(~n + 1);//diff between n and 32
return !(x ^ ((x << diff) >> diff)); //shifts x left by diff then right by diff leaving the num unchanged if it would fit as an n-bit 2s comp int then xor's with x so it will be !0 if x matches shifted x or !1 otherwise
}