美文网首页Interview Questions
Identify the last character

Identify the last character

作者: 宋翰要长肉 | 来源:发表于2016-03-26 05:11 被阅读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 is double
      • otherwise, traverse from last slice to first slice and count the number of 1 at first bit in each slice until the first bit is 0
        • if the number of 1 is even, the last character is single
        • otherwise, the last character is double

    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)

    相关文章

      网友评论

        本文标题:Identify the last character

        本文链接:https://www.haomeiwen.com/subject/uvsdlttx.html