任务是合并2个给定数字的二进制数。
示例:
给定5
(101
)和3
(011
),结果为46
(concat(101, 011) = 101011
)
到目前为止的代码:
public class Concat {
public static void main(String[] args) {
int t = 0;
int k = 5;
int x = 3;
int i = 0;
while (i < 3) {
t = x % 2;
x /= 2;
k <<= 1;
k |= t;
++i;
}
System.out.println(k);
}
}
但是问题在于上面的代码给出了
101110
,而不是101011
。有什么问题?
最佳答案
您的问题是您要向后喂第二个数字的位。那是因为x%2
是低阶位:
+---+---+---+ <110
| 1 | 0 | 1 | <-----------------+^
+---+---+---+ |1
+---+---+---+ |1
| 0 | 1 | 1 | ----+0
+---+---+---+ 011>
赞叹我超凡的艺术能力:-)但是,如果您已经知道它只有3位宽,请使用:
public class concat {
public static void main (String[] args) {
int t = 0;
int k = 5;
int x = 3;
k <<= 3;
k |= x;
// or, in one line: k = (k << 3) | x;
System.out.println(k);
}
}
就图形外观而言:
+---+---+---+
k:| 1 | 0 | 1 |
+---+---+---+
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
+---+---+---+---+---+---+
k<<=3:| 1 | 0 | 1 | 0 | 0 | 0 |
+---+---+---+---+---+---+
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
+---+---+---+---+---+---+
k|=3:| 1 | 0 | 1 | 0 | 1 | 1 |
+---+---+---+---+---+---+
^ ^ ^
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
没有明显的理由一次这样做。