欢迎访问
讨论版列表 - 算法集锦 - 主题数: 41 | 文章数: 47 | 管理员: homecox

算法集锦

版面 | 文摘区 | 马克区

文章数: 1 | 分页: << 1 >>
admin
[回复] [修改] [删除] [返回版面] 1  
作者: admin, 讨论版: 算法集锦, 发表时间: 2014-01-07 15:41:41 PST
标题: Byte Array encoding
关键字:

Given a byte array, which is an encoding of characters. Here is the rule:
    a. If the first bit of a byte is 0, that byte is a one-byte character
    b. If the first bit of a byte is 1, that byte and its following byte
       together stand for a two-byte character

Now implement a function to decide if the last character is a one-byte character or a two-byte character. You must scan the byte array from the end to the start. Otherwise it is very trivial.

思路:

B1....Bn.
从后往前:
   如果Bn是1开头,那么2字节结尾。
   如果Bn是0开头,看Bn-1:
      如果是0开头,无论Bn-1是自己管自己还是Bn-2的附属,都不影响Bn,所以1字节结尾。
      如果是1开头就要继续看前面,记录下已经看到的1开头的个数C.

直到找到一个0开头的或者到头了就结束。

如果C偶数,那么1字节结尾。
如果C为奇数,那么2字节结尾。

例如:

Bn
1 -> 2-byte end
0 -> need to look at Bn-1:

Bn-1 Bn
0    0 -> 1-byte end
1    0 -> need to look at Bn-2:

Bn-2 Bn-1 Bn
0    1    0 -> 2-byte end
1    1    0 -> need to look at Bn-3:

Bn-3 Bn-2 Bn-1 Bn
0    1    1    0 -> 1-byte end
1    1    1    0 -> need to look at Bn-4:
...


代码:

bool firstBitIsOne(unsigned char c) { return (c >> 7) & 1; } // return number of bytes in the last byte. int lastByteCount(string s) { int n = s.length(); if (n == 0) return 0; if (firstBitIsOne(s[n-1])) return 2; int i = n-2; for (; i >= 0 && firstBitIsOne(s[i]); -- i) {} if ((n - i) & 1) return 2; // odd number of 1s. else return 1; }
来自: http://www.mitbbs.com/article_t/JobHunting/32605453.html


--

最后修改: admin on 2014-01-07 15:49:53 PST
※ 来源: homecox.com  [来自: 128.]


Reply

Please log in first.