2014-03-19 06:33
题目:用一个byte数组来模拟WxH的屏幕,每个二进制位表示一个像素。请设计一个画水平线的函数。
解法:一个点一个点地画就可以了。如果要优化的话,其实可以把中间整字节的部分一口气画了,只用1/8的力气。
代码:
1 // 5.8 Given a byte array, set a consecutive bit segment to '1'. 2 #include <cstdio> 3 #include <vector> 4 using namespace std; 5 6 typedef unsigned char byte; 7 8 inline void setBit(vector<byte> &v, int i, int j, int w) 9 { 10 v[i * w / 8 + j / 8] |= (1 << (j - (j >> 3 << 3))); 11 } 12 13 inline int getBit(vector<byte> &v, int i, int j, int w) 14 { 15 return !!(v[i * w / 8 + j / 8] & (1 << (j - (j >> 3 << 3)))); 16 } 17 18 int main() 19 { 20 int n, w, h; 21 int x1, x2, y; 22 vector<byte> v; 23 int i, j; 24 25 while (scanf("%d%d", &n, &w) == 2) { 26 h = n * 8 / w; 27 v.resize(n); 28 for (i = 0; i < n; ++i) { 29 v[i] = 0; 30 } 31 scanf("%d%d%d", &x1, &x2, &y); 32 33 // boundary check is omitted. 34 for (i = x1; i <= x2; ++i) { 35 setBit(v, y, i, w); 36 } 37 38 for (i = 0; i < h; ++i) { 39 for (j = 0; j < w; ++j) { 40 putchar('0' + getBit(v, i, j, w)); 41 } 42 putchar(' '); 43 } 44 } 45 46 return 0; 47 }