Identify the last character
2016-03-26 本文已影响15人
宋翰要长肉
Qestion
- input: an integer array with 1 or 0 for each index
- output: last character is double or single character
- 0XXXXXXX: Single character
- 1XXXXXXX XXXXXXX: Double character
Algorithm
- split the input by 8 length
- check the first bit of last byte
- if it is
1
, then the last character isdouble
- otherwise, traverse from last slice to first slice and count the number of
1
at first bit in each slice until the first bit is0
- if the number of
1
is even, the last character issingle
- otherwise, the last character is
double
- if the number of
- if it is
Code
public String doubleOrSingLastChar(int[] input) {
int len = 8;
int i = input.length - 8;
if (input[i] == 1) {
return "Double";
}
i -= len;
int count = 0;
while (i >= 0 && input[i] == 1) {
count++;
i -= len;
}
if (count % 2 == 1) {
return "Double";
} else {
return "Single";
}
}
Complexity
- time complexity:
O(N)
- space complexity:
O(1)