2017-07-25 103 views
-2

给出整数n,值v(v = 0或1)和位置p。编写一个修改n的运算符序列,使n的二进制表示在位置p保存值v。例如:Java简单按位运算

  • N = 5(00000101)中,p = 3,V = 1 - > 13(00001101)
  • N = 5(00000101)中,p = 2,V = 0 - > 1(00000001 )

这是我的代码:

int n1 = 35; 
int p1 = 3; 
int v = 1; 
n1 = n1 + (v << p1); 
System.out.println(n1); 

它的工作原理时,v = 1而当v = 0它没有。

+0

使用总和,如果v = 0,你加0(移位不改变它是0的事实),所以该值不会改变。您可能想在那里寻找不同的操作。可能有点操作。 – bracco23

+0

我没有回答解决方案,因为这绝对看起来像一个任务,你应该可以自己做到。 – bracco23

+0

@ bracco23它看起来像一个任务,对于这样的事情,我通常提供没有代码的方法。希望你不介意。干杯。 –

回答

0

既然要“集”的索引值,你需要两个中的一个操作

'and' will set 0 values at an index to 0, but won't work for 1 values 
'or' will set 1 values at an index to 1, but won't work for 0 values 

现在你需要做的就是把正确数量的正确索引。这可以通过转移1

'<<' moves the 1 a number of places 

例如

'1 << 3' shifts the 1 three places, resulting in '00001000' 

记得要做,我们需要一个零的一些操作,在那个地方得到一个零,你需要反转位

'not' or '~' flips all the bits in a number 

~00001000 yeilds 11110111 

现在我们可以有1或我们希望,并且只需要使用if语句来挑基础上所需的操作是正确的,并应用相应的and或指数操作来设置我们想要的位。

0

好吧我认为这是行得通的,但是如何在控制台上正确打印结果呢?

// Swapping i and j: i ^= j, j ^= i, i ^= j; 
    // Getting the pth byte: (n >> p) & 1 
    // Setting the pth byte to v: (v == 0) ? (n & ~(1 << p)) : (n | 1 << p) 
    static int Exchange(int n, int i, int j) 
    { 
     n = ((n >> i) & 1^(n >> j) & 1) == 0 ? (n & ~(1 << j)) : (n | 1 << j); 
     n = ((n >> i) & 1^(n >> j) & 1) == 0 ? (n & ~(1 << i)) : (n | 1 << i); 
     n = ((n >> i) & 1^(n >> j) & 1) == 0 ? (n & ~(1 << j)) : (n | 1 << j); 

     return n; 
    } 

    public static void main(String[] arguments) 
     { 
      int n = 56, p = 3, q = 24, k = 3; 

      while (k-- != 0) n = Exchange(n, p++, q++); 
     }