-2

We are given integer n, value v (v=0 or 1) and a position p. Write a sequence of operators that modifies n to hold the value v at the position p from the binary representation of n. Example:

  • n = 5 (00000101), p=3, v=1 -> 13 (00001101)
  • n = 5 (00000101), p=2, v=0 -> 1 (00000001)

This is my code:

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

It works when the v=1 but when the v=0 it doesn't.

k1op0ly
  • 1
  • 1
  • 1
  • 2
  • Using the sum, if v=0, you are adding 0 (shifting does not change the fact that it is 0), so the value doesn't change. You might want to look for a different operation there. Probably a bit operation. – bracco23 Jul 25 '17 at 14:32
  • I'm not answering with the solution because this definitely looks like an assignment, you should be able to achieve that by yourself. – bracco23 Jul 25 '17 at 14:33
  • @bracco23 It does look like an assignment, and for such things I typically offer approaches without code. Hope you don't mind. Cheers. – Edwin Buck Jul 25 '17 at 14:41

2 Answers2

0

Since you want to "set" the index to a value, you need one of two operations

'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

Now all you need to do is put the right number at the right index. This can be done by shifting 1.

'<<' moves the 1 a number of places

for example

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

remember, we need a zero for some of the operations, to get a zero in that place, you need to invert the bits

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

~00001000 yeilds 11110111

Now we can have a 1 or a 0 in the index we wish, and only need to use an if statement to pick the right one based on the desired operation and apply the corresponding and or or operation to set the bit we want.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
0

Okay I think that is going to work, but how to print the result properly on the console?

    // 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++);
        }
k1op0ly
  • 1
  • 1
  • 1
  • 2