-2

Given an n × n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.

enter image description here

class Solution {
    public int[][] flipAndInvertImage(int[][] image) {
        for (int i = 0; i < image.length; i++) {
            for (int j = image[0].length - 1; j >= 0; j--) {
                image[i][j] ^= 1;
                System.out.printf("%d ", image[i][j]);
            }
        }
        return image;
    }
}

This is my approach but when I return the 2D array not getting the desired output but you can see the stdout is printing result. May I know where I am going wrong

Abra
  • 19,142
  • 7
  • 29
  • 41
  • 1
    You haven't reversed the rows. Just printing backwards won't reverse it. – nice_dev Jul 25 '22 at 04:45
  • First see here to [reverse each inner array](https://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java) then finally do your bit flip. – sorifiend Jul 25 '22 at 04:54

1 Answers1

0

You're just printing the array not modifying it, You can modify the array using code below

public int[][] flipAndInvertImage(int[][] image) {
    int[][] newImage = new int[image.length][image.length];
    int l = 0, m;
    for (int[] ints : image) {
        m = 0;
        for (int j = image[0].length - 1; j >= 0; j--) {
            newImage[l][m++] = ints[j] ^ 1;
        }
        l++;
    }
    return newImage;
}
Sidharth Mudgil
  • 1,293
  • 8
  • 25