Java in place and using bit operations

  • 0
    public int[][] imageSmoother(int[][] M) {
            if(M==null || M.length == 0)
                return M;
            int rows = M.length;
            int cols = M[0].length;
            for(int i=0; i<rows; i++){
                for(int j=0; j<cols; j++){
                    int top = Math.max(0, i-1);
                    int bottom = Math.min(rows-1, i+1);
                    int left = Math.max(0,j-1);
                    int right = Math.min(cols-1, j+1);
                    int sum=0, count=0;
                    for(int x=top; x<=bottom; x++){
                        for(int y=left; y<=right; y++){
                            // & with 255 will mask any offset greater
                            // than 255 and retain only 0 to 255
                            sum+= (M[x][y] & 255);
                    //Push the new state 8 bits to left
                    //to retain old state
                    M[i][j] += (sum/count)<<8;
            for(int i=0; i<rows; i++)
                for(int j=0; j<cols; j++)
                    //Throw off the old state (LSB 8 bits)
                    M[i][j] = M[i][j]>>8;
            return M;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.