1-bit and 2-bit Characters

topic:We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).

Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

翻译:我们有两个特殊字符。第一个字符可以用一个比特0表示。第二个字符可以用两个比特(10或11)表示。
现在给出一个由几位表示的字符串。返回最后一个字符是否必须是一位字符。给定的字符串将始终以零结尾。

解题思路:利用一个游标(i)指向数组的第一个数,然后对数组进行遍历
判断条件:若此数为零,则i+1;否则i+2;
结束条件:i>=array.length-1(最后一个数为判断字符,无需遍历)

重点:最后一个字符是否必须是一位字符的判断条件:

判断条件

实现代码

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
26
27
28
29
30
31
32
33
34
35
36
public class Solution {
public static void main(String arg[])
{
Solution s=new Solution();
int bit[]={1,1,0,1,0,1,0};
boolean a=s.fun(bit);
System.out.println(a);
}
public boolean fun(int[] bit) {
int len=bit.length;
int i=0;
while(i<len-1)
{
if(bit[i]==0)
{
if(i<len)
i=i+1;
else
break;
}
else {
if(i<len)
i=i+2;
else
break;
}
}
System.out.println(i);
if(i==len-1|| (i==len-2 && bit[i]==1))
return true;
else
return false;

}

}

最后更新: 2018年11月29日 16:07

原始链接: https://LiYuanSh.github.io/2018/11/29/leetcode1/

× 请我吃糖~
打赏二维码