0%

面试题 05.08. 绘制直线

面试题 05.08. 绘制直线

题意可真难懂

给出的length表示一维int数组的长度,那么这个屏幕总共有length * 32位,每一位表示一个像素

w表示每一行的宽度。例如,如果每行宽度为96,就表示这一行由3个int组成,在一维数组中占用3个元素。由此可以推算出高度为w / 3

接下来进行位运算就好了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
vector<int> drawLine(int length, int w, int x1, int x2, int y) {
int h = length * 32 / 96;
int sh = w / 32;
vector<int> ret(length, 0);
int startLine = x1 / 32 + y * sh;
int endLine = x2 / 32 + y * sh;
x1 %= 32;
x2 %= 32;
for(int i = startLine + 1; i < endLine; ++i)
ret[i] = -1;
if(startLine == endLine)
{
ret[startLine] += static_cast<unsigned int>(1 << (31 - x1)) - 1 - ((1 << (31 - x2)) - 1);
ret[startLine] |= 1 << (31 - x1);
}else
{
ret[startLine] |= 1 << (31 - x1);
ret[startLine] += static_cast<unsigned int>(1 << (31 - x1)) - 1;
ret[endLine] = ~((1 << (31 - x2)) - 1);
}
return ret;
}
};

稍微优化一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> drawLine(int length, int w, int x1, int x2, int y) {
int sh = w / 32;
vector<int> ret(length, 0);
int startLine = x1 / 32 + y * sh;
int endLine = x2 / 32 + y * sh;
x1 %= 32;
x2 %= 32;
for(int i = startLine + 1; i <= endLine; ++i)
ret[i] = -1;
ret[startLine] |= 1 << (31 - x1);
ret[startLine] += static_cast<unsigned int>(1 << (31 - x1)) - 1;
ret[endLine] &= ~((1 << (31 - x2)) - 1); // 这样子就可以不管startLine == endLine的情况了
return ret;
}
};