Google Interview Question
Developer Program EngineersCountry: United States
Interview Type: Phone Interview
Awesome dude. Only one question/suggestion. I think the following for loop:
// Then set the start/end byte
for ( int i = 0; i < byteStartBit; i++ ) {
img[startByte] = img[startByte] | 1 << (8-i);
}
should be
for ( int i = byteStartBit; i < 8; i++ ) {
img[startByte] = img[startByte] | 1 << (8-i);
}
You don't want to set the bits from left to byteStartBit, you want to set from byteStartBit to the end of the byte (going right)
void drawLine(byte[] img, int len, int wid, int r, int x1, int x2) {
for(int i=wid*r+x1; i<=wid*r+x2;i++) {
img[i]=1; //in java, we need not worry about of array index out of bounds, as jvm throws this error if i is going out of range of img array last index. Otherwise, we can add a check i<=img.length
}
I don't get this qn. Can you please clarify with an example? What I make out is, byte[] img is a 2D array whose width is 8 (8 bits). In this 2D array, we have to set x1->x2 in row r as 1. Right? If this is the case, then length and width are not required. My solution for this case would be -
void drawLine(byte[] img, int len, int wid, int r, int x1, int x2) {
byte[r] = 0; // let x1 = 3, x2 = 5;
byte[r] << (x2-x1+2); // byte[r] = 00001000
byte[r] = byte[r] - 1; // byte[r] = 00000111
byte[r] = byte[r] << (8-x2); //byte[r] = 00111000
}
public class DrawLine {
static void drawLine(byte[] img, int len, int wid, int r, int x1, int x2) {
int nbyte = wid/8;
printImg(img, wid);
for (int i = x1; i <= x2; i++) {
int index = getIndex(i, r, nbyte);
int bitPos = getBitPos(i, nbyte);
img[index] = (byte) (img[index] | (0x80 >> bitPos));
}
System.out.println();
printImg(img, wid);
}
static int getIndex(int x, int row, int nbyte) {
return (row-1)*nbyte + (x >> 3);
}
static int getBitPos(int x, int nbyte) {
return (x - ((x >> 3) << 3));
}
static void printImg(byte[] img, int wid) {
int row = img.length * 8 /wid;
int nbyte = wid/8;
for (int r = 1; r <= row; r++) {
for (int i = 0; i< wid; i++) {
int index = getIndex(i, r, nbyte);
int bitPos = getBitPos(i, nbyte);
if ((img[index] & (0x80 >> bitPos)) > 0) System.out.print("1");
else System.out.print("0");
}
System.out.println();
}
}
public static void main(String[] args) {
byte[] img = new byte[32];
drawLine(img, 0, 32, 7, 9, 31);
}
}
Suppose using Java, unless we need bound check, there's no need for 'len'
- flamearrow February 02, 2013