【问题标题】:Solving Binary Gap using Recursion使用递归解决二进制间隙
【发布时间】:2016-06-02 14:05:18
【问题描述】:

我正在尝试使用递归解决二进制间隙问题。无需递归即可轻松解决。但是我想用递归来解决这个问题。下面的程序将一个整数作为输入并找到二进制间隙。

例子:

input= 9, Binary form = 1001, Answer = 2

input=37, Binary form = 100101, Answer = 2

它找出二进制表示中两个 1 之间出现的最大零数。

我想在 O(logn) 中解决这个问题。现在,下面的程序只是简单地计算零的总数并给出输出 3 而不是 2。我该如何纠正这个以获得正确的输出?

class BinaryGap {

    public int solution(int N){

     return solution(N, false, 0);   
    }
    public int solution(int N, boolean prevFlag, int memo) {

        if(N<2)
            return 0;

        int remainder = N%2 ;


        if(prevFlag){
            if(remainder == 0){
                memo = 1 + solution(N/2, prevFlag, memo);
            } else {
                int newGap = solution(N/2, prevFlag, memo);

                if(newGap > memo)
                    memo = newGap;
            }
        } else {

            prevFlag = (remainder == 1);
            return solution(N/2, prevFlag, 0);
        }

        return memo;

    }

    public static void main(String args[]){
        BinaryGap obj = new BinaryGap();

        System.out.println(obj.solution(37));
    }

}

【问题讨论】:

    标签: java algorithm recursion binary time-complexity


    【解决方案1】:

    试试这个。

    static int solution(int n) {
        return solution(n >>> Integer.numberOfTrailingZeros(n), 0, 0);
    }
    
    static int solution(int n, int max, int current) {
        if (n == 0)
            return max;
        else if ((n & 1) == 0)
            return solution(n >>> 1, max, current + 1);
        else
            return solution(n >>> 1, Math.max(max, current), 0);
    }
    

    int[] tests = { 9, 37, 0b1000001010001 };
    for (int i : tests)
        System.out.printf("input = %d, Binary form = %s, Answer = %d%n",
            i , Integer.toBinaryString(i), solution(i));
    

    输出

    input = 9, Binary form = 1001, Answer = 2
    input = 37, Binary form = 100101, Answer = 2
    input = 4177, Binary form = 1000001010001, Answer = 5
    

    这是简单的尾递归。所以你可以这样写而不用递归。

    static int solutionLoop(int n) {
        int max = 0;
        for (int i = n >>>= Integer.numberOfTrailingZeros(n), current = 0; i != 0; i >>>= 1) {
            if ((i & 1) == 0)
                ++current;
            else {
                max = Math.max(max, current);
                current = 0;
            }
        }
        return max;
    }
    

    n &gt;&gt;&gt; Integer.numberOfTrailingZeros(n) 删除 n 中的尾随零。

    【讨论】:

    • 它有效。你能告诉我一些可以用来提高我的递归写作技巧的好资源吗?
    • 但是例如,您的解决方案不适用于 100。它应该肯定返回 0。
    • 它不适用于以零结尾的数字。例如。 8
    • 我会先添加类似:while (n % 2 == 0 &amp;&amp; n &gt; 0) n &gt;&gt;= 1;
    • 用输入测试:100010000 但是,它返回 6 作为结果,这是错误的。
    【解决方案2】:

    在 Java 8 中,您可以使用流来解决这个问题:

    static int calculateBinaryGap(int N) {
        return Stream
            .of(
                // integer to binary string
                Integer.toBinaryString(N)
                    // trim 0(s) at the end
                    .replaceAll("0+$", "")
                    // split string with 1(s)
                    .split("1+"))
            // lambda expressions: use filter to keep not null elements
            .filter(a -> a != null)
            // method references: convert string to integer by using the
            // length of string
            .map(String::length)
            // method references: find the largest number in the stream by
            // using integer comparator
            .max(Integer::compare)
            // return 0 if nothing matches after the process
            .orElse(0);
        }
    

    有一篇关于Streams的好文章:Processing Data with Java SE 8 Streams

    【讨论】:

      【解决方案3】:

      我们可以用1作为分隔符来分割binaryString

      例如: N=1041 二进制字符串 = 10000010001

      当它以 1 为分隔符拆分时 我们得到 [, 00000, 000]

      然后子问题变成了找到最大长度的数组

      private static int solution(int N) {
              int gap = 0;
              String binaryStr = Integer.toBinaryString(N);
      
              String[] zeroArrays = binaryStr.split("1");
              System.out.println(Arrays.toString(zeroArrays));
              for(String zeroArray : zeroArrays) {
                  gap = zeroArray.length() > gap ? zeroArray.length() : gap;
              }   
              return gap;
          }
      

      【讨论】:

      • 如果二进制是: 1000100000 怎么办?您的代码返回 5 这是不正确的。它应该返回 3。因为最后一组零在结尾处不受 1 的约束。
      • for loop中检查zeroArray 是否以0结尾然后不要考虑。
      【解决方案4】:

      我认为@saka1029 几乎就在那里,就像@xuesheng 所说,如果输入例如 2 = 010、4 = 100、6 = 110,解决方案将不起作用。

      我想建议在下面这样做

      static int solution(int n) {
          return solution(n, 0, 0, 0);
      }
      
      static int solution(int n, int max, int current, int index) {
          if (n == 0)
              return max;
          else if (n % 2 == 0 && index == 0)
              return 0;
          else if (n % 2 == 0 && index > 0)
              return solution(n / 2, max, current + 1, index + 1);
          else
              return solution(n / 2, Math.max(max, current), 0, index + 1);
      }
      

      【讨论】:

        【解决方案5】:

        hemantvsn 的解决方案很好,除了需要删除的尾随零

        private static int solution(int N) {
                    int gap = 0;
                    String binaryStr = Integer.toBinaryString(N);
        
                    String[] zeroArrays = binaryStr.split("1");
        
                    String[] zeroTruncated = new String[0];
        
                    System.out.println(Arrays.toString(zeroArrays));
                    if (Integer.lowestOneBit(N) != 1) {
                        zeroTruncated = Arrays.copyOf(zeroArrays, zeroArrays.length-1);
        
                    }
                    for(String zeroArray : zeroTruncated) {
                        gap = zeroArray.length() > gap ? zeroArray.length() : gap;
                    }
                    return gap;
                }
        

        【讨论】:

          【解决方案6】:

          由于许多人在处理解决方案的尾随零条件时遇到了问题。 以下是我通过 100% 测试用例的解决方案。

          class Solution {
              public int solution(int N) {
                  // write your code in Java SE 8
                  return binaryGap(N,0,0,0);
              }
              public int binaryGap(int n, int counter, int max, int index){
                  if(n==0)
                      return max;
          
                  if(n%2==0 && index==0)
                      index=0;
          
                  else if(n%2==0)
                      counter ++;
                  else {
                      max = Math.max(counter, max);
                      index++;
                      counter =0;
                  }
                  n = n/2;
          
                  return binaryGap(n, counter, max, index);
              }
          
          }
          

          【讨论】:

            【解决方案7】:

            目标 C 解决方案

            int solution(int N) {
                if (N==0)
                {
                    return 0;
                }
                int maximumGap = -1;
                int currentGap = 0;
                while(N>0)
                {
                    if (N%2 == 1)
                    {
                        if (currentGap>0)
                        {
                            maximumGap = maximumGap>currentGap?maximumGap:currentGap;
                        }else
                        {
                            maximumGap = 0;
                        }
                        currentGap = 0;
                    }
                    else if(maximumGap>-1)
                    {
                        currentGap++;
                    }
                    N=N/2;
                }
                return maximumGap;
            }
            

            【讨论】:

              【解决方案8】:

              我的解决方案。 100% 没有递归。

              class Solution {
                      public int solution(int N) {
                          String binary = Integer.toString(N, 2);
                          int largestGap = 0;
                          for (int i = 1, gap = 0; i < binary.length(); i++) {
                              while (i < binary.length() && binary.charAt(i) == '0') {
                                  i++;
                                  gap++;
                              }
              
                              if (gap > largestGap && i < binary.length()) {
                                  largestGap = gap;
                              }
              
                              gap = 0;
                          }
                          return largestGap;
                      }
                  }
              

              【讨论】:

              • 这部分是不是 { pos++; } 需要吗?似乎不能有其他 0 的值,因为二进制数总是以 1 开头,而当有 1 值时,则从内部循环中逃脱。或者它会手动考虑某些类型的 String 二进制文件,而不是从解析中。
              • 好吧@MichałZiobro ...你是对的...我又成功了。
              【解决方案9】:

              试试这个。不使用递归我累了。

              private static int binaryGap(int N){
                  int gap1 = 0, gap2 = 0, gapCounter = 0;
              
                  for(int i = N; i>=0; i--)
                  {
                      if(N < 1) break;
              
                      //binary 0
                      if(N%2 == 0) {
                          gap1++;
                      }
                      //binary 1
                      else
                      {
                          gap2 = gap2 > gap1 ? gap2 : gap1;
                          gap1 = 0;
                          gapCounter++;
                      }
                      if(gapCounter==1) gap2=0;
                      N = N/2;
                  }
                  return gap2;
              }
              

              【讨论】:

                【解决方案10】:
                // you can write to stdout for debugging purposes, e.g.
                // printf("this is a debug message\n");
                
                int solution(int N) {
                   int b;
                    int zeroCounter = 0;
                    int prev = 0;
                    int c = -1;
                    while (N) {
                        b = N % 2;
                        N = N / 2;
                        if ((b==1)||(c==0)) {
                           c=0;
                
                            //printf("%d", b);
                            if (b == 1) {
                
                                //printf("%d", b);
                                //checkTrailZero=prev;
                                if (prev < zeroCounter) {
                                    prev = zeroCounter;
                                }
                                zeroCounter = 0;
                            } else {
                
                                zeroCounter++;
                            //  printf("--%d--", zeroCounter);
                            }
                        }
                    }
                    //printf("longest%d", prev);
                    return prev;}
                

                【讨论】:

                • 测试分数 codility 100% 100 分,满分 100 分。使用的编程语言:C 使用的总时间:70 分钟 使用的有效时间:70 分钟 注意:尚未定义任务时间表
                • 欢迎来到 SO。请将您的附加信息编辑到答案中。另外,请考虑添加几行解释。
                【解决方案11】:

                这是所有测试用例都通过的工作代码,

                package org.nishad;
                
                import java.util.Arrays;
                
                public class BinaryGap {
                    public static void main(String[] args) {
                        int N = 1;
                        int result;
                        //converting integer to binary string
                        String NString = Integer.toBinaryString(N);
                        //Removing the Trailing Zeros
                        NString = NString.replaceFirst("0*$","");
                        //Split the binary string by one or more one(regex) for arrays of zeros 
                        String[] NStrings = NString.split("1+");
                        //Storing the array length
                        int length = NStrings.length;
                
                        if(length==0) // if length is zero no gap found 
                            result = length;
                        else          
                            {
                            //Sorting the array to find the biggest zero gap
                            Arrays.sort(NStrings, (a, b)->Integer.compare(a.length(), b.length()));
                            result = NStrings[length-1].length();
                            }
                
                
                        System.out.println(NString);
                
                        System.out.println(result);
                    }
                }
                

                【讨论】:

                  【解决方案12】:

                  Java 解决方案(无递归 - Codility 100% 正确):

                  public static int solution(Integer number) {
                  
                      String binary = Integer.toBinaryString(number);
                  
                      String[] gaps = binary.split("1");
                  
                      String biggestGap ="";
                      for (int i = 0; i < (binary.endsWith("1") ? gaps.length: gaps.length-1); i++) {
                  
                          if (gaps[i].contains("0") && gaps[i].length()>biggestGap.length())
                          biggestGap = gaps[i];
                  
                      }
                  
                      return biggestGap.length();
                  }
                  

                  【讨论】:

                    【解决方案13】:

                    请做吧:

                    class Solution {
                        public int solution(int N) {
                            int gap = 0;
                            int current = -1;
                    
                            while(N>0) {
                                if(N%2!=0) {
                                   if(current>gap)
                                        gap = current;
                                    current = 0;
                                } else if(current>=0){
                                     current++;
                    
                                }
                                N=N>>1;
                                }
                    
                                return gap;
                        }
                    }
                    

                    权威!

                    谢谢!!!!

                    【讨论】:

                    • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
                    【解决方案14】:

                    十进制转二进制时的Javascript解决方案。

                    function solution(N) {
                        let maxGap = 0, currentSegmentGap = 0;
                    
                        let init = false;   
                    
                        while(N > 0) {
                            const binDgt = N%2;
                    
                            if(binDgt) {
                                currentSegmentGap = 0;
                                init = true;
                    
                            } else if(init) {
                                currentSegmentGap++;
                                maxGap = maxGap > currentSegmentGap? maxGap: currentSegmentGap;
                            }
                    
                            N = Math.floor(N/2);
                        }
                        return maxGap;
                    }
                    

                    【讨论】:

                      【解决方案15】:

                      Java 解决方案(在 Codility 中 100% 正确)

                      int solution(int N) {
                          int tempGap=0, gap=0;
                          String binaryString = Integer.toBinaryString(N);
                          int i =0;
                          while(i < binaryString.length())    {
                              if(binaryString.charAt(i) == '1')   {
                                  // initialize tempGap to hold binary gap temporarily and increment the index pointing to binary array
                                  ++i;
                                  tempGap = 0;
                                  // move until we encounter '1' or end of array is reached
                                  while(i < binaryString.length() && binaryString.charAt(i) != '1')    {
                                      ++i;
                                      tempGap++;
                                  }
                                  // in case, end of array is reached but we did not find '1'
                                  if (i >= binaryString.length())    {
                                      tempGap = 0;
                                  }
                              } else  {
                                  ++i;
                              }
                              if (tempGap>gap)    {
                                  gap = tempGap;
                              }
                          }
                          return gap;
                      }
                      

                      【讨论】:

                        【解决方案16】:
                        int solution(N) {
                        
                           int num = N,
                            currentLongest=0,
                            lastLongest=0,
                            start=0;
                        
                          while(num>0){
                            int rem = num%2;
                                num = num/2;
                        
                            if(rem == 1){
                                if(lastLongest < currentLongest){
                                    lastLongest = currentLongest;
                                }
                                currentLongest = 0;
                                start = true;
                            }else{
                                if(start)
                                 ++currentLongest;
                               }
                           }
                          return lastLongest;
                        }
                        

                        【讨论】:

                        • 没有给出代码或描述的解释
                        【解决方案17】:

                        我在没有使用递归的情况下得到了这个解决方案。

                        def solution(N):
                            number = str(bin(N))[2:]
                        
                            current = 0
                            max_ = 0
                            started = False
                            for e in number[::-1]:
                                if e == '1':
                                    started = True
                                    if current > max_:
                                        max_ = current
                                    current = 0
                                else:
                                    if started:
                                        current = current + 1
                            return max_
                        

                        【讨论】:

                          【解决方案18】:

                          我的解决方案是用 Swift 4 编写的,具有完全不同的逻辑(没有递归),它可以找到最长的二进制间隙,也有助于找到当前的二进制间隙。 100% 测试用例通过。

                          复杂度:O(n)

                          public func solution(_ N : Int) -> Int {
                          
                              var arrayOfIndexes:[Int] = []
                              let binaryString = String(N, radix:2)
                          
                              print("Binary String of \"\(N)\" is: \"\(binaryString)\"")
                          
                              var longestBinaryGap:Int = 0
                              var index = 0
                          
                              for char in binaryString {
                                  if char == "1" {
                                      arrayOfIndexes.append(index)
                                      let currentBinaryGap = getCurrentBinaryGapFor(arrayOfIndexes)
                                      if arrayOfIndexes.count == 2 {
                                          longestBinaryGap = currentBinaryGap
                                      } else if index > 2 {
                                          if currentBinaryGap > longestBinaryGap {
                                              longestBinaryGap = currentBinaryGap
                                          }
                                      }
                                  }
                                  index += 1
                              }
                          
                              print("Position of 1's: \(arrayOfIndexes)")
                              return longestBinaryGap
                          }
                          
                          func getCurrentBinaryGapFor(_ array:[Int]) -> Int {
                              var currentBinaryGap = 0
                              if array.count >= 2 {
                                  let currentPosition = array.count - 1
                                  let previousPosition = currentPosition - 1
                                  currentBinaryGap = array[currentPosition] - array[previousPosition] - 1
                                  return currentBinaryGap
                              } else {
                                  return currentBinaryGap
                              }
                          }
                          

                          带输出的示例测试用例:

                          Binary String of "2" is: "10"
                          Position of 1's: [0]
                          The longest binary gap is 0
                          
                          Binary String of "4" is: "100"
                          Position of 1's: [0]
                          The longest binary gap is 0
                          
                          Binary String of "6" is: "110"
                          Position of 1's: [0, 1]
                          The longest binary gap is 0
                          
                          Binary String of "32" is: "100000"
                          Position of 1's: [0]
                          The longest binary gap is 0
                          
                          Binary String of "170" is: "10101010"
                          Position of 1's: [0, 2, 4, 6]
                          The longest binary gap is 1
                          
                          Binary String of "1041" is: "10000010001"
                          Position of 1's: [0, 6, 10]
                          The longest binary gap is 5
                          
                          Binary String of "234231046" is: "1101111101100001010100000110"
                          Position of 1's: [0, 1, 3, 4, 5, 6, 7, 9, 10, 15, 17, 19, 25, 26]
                          The longest binary gap is 5
                          

                          【讨论】:

                            【解决方案19】:

                            @saka1029 提供了一个很好的解决方案,但它并没有涵盖所有的测试用例。 这是一个涵盖所有情况的解决方案。

                            公共 int 解决方案(int N){

                                return solution(N, 0, 0, false);
                            }
                            
                            static int solution(int n, int max, int count, boolean isOn) {
                                if (n == 0)
                                    return max;
                                else if (n % 2 == 0){
                                    count = isOn? count+1 : count;
                                    return solution(n / 2, max, count, isOn);
                                }
                                else{
                                    isOn=true;
                                    max = count>max?count:max;
                                    return solution(n / 2, Math.max(max, count), 0, isOn);
                                }
                            }
                            

                            【讨论】:

                              【解决方案20】:

                              最佳解决方案考虑了边界和异常情况,例如:给定 N = 32,函数应返回 0,因为 N 具有二进制表示“100000”,因此没有二进制间隙。 但我在上面看到的大多数代码都会返回 5。 这是错误的。 这是通过所有测试的最佳解决方案:

                              public int solution(int N) {
                                      int result = 0;
                                      while (N > 0) {
                                          if ((N & 1) == 1) {
                                              int temp = 0;
                                              while ((N >>= 1) > 0 && ((N & 1) != 1)) {
                                                  temp++;
                                              }
                                              result = Math.max(result, temp);
                                          } else {
                                              N >>= 1;
                                          }
                                      }
                                      return result;
                                  } 
                              

                              【讨论】:

                                【解决方案21】:

                                这是另一个Java解决方案(递归和迭代版本),时间复杂度O(log n),100%正确,即处理尾随零条件,避免使用整数二进制字符串.

                                递归:

                                class Solution {
                                
                                    public int solution(int N) {
                                        return binaryGapRecursive(N, 0, null);
                                    }
                                
                                    private int binaryGapRecursive(int n, int maxGap, Integer currentGap) {
                                        int quotient = n / 2;
                                
                                        if (quotient > 0) {
                                            int remainder = n % 2;
                                
                                            if (remainder == 1) {
                                                if (currentGap != null) {
                                                    maxGap = Math.max(maxGap, currentGap);
                                                }
                                                currentGap = 0;
                                
                                            } else if (currentGap != null) {
                                                currentGap++;
                                            }
                                
                                            return binaryGapRecursive(quotient, maxGap, currentGap);
                                
                                        } else {
                                            return currentGap != null ? Math.max(maxGap, currentGap) : maxGap;
                                        }
                                    }
                                
                                }
                                

                                迭代:

                                class Solution {
                                
                                    public int solution(int n) {
                                        int maxGap = 0;
                                        Integer currentGap = null;
                                
                                        while (n > 0) {
                                            int remainder = n % 2;
                                
                                            if (remainder == 1) {
                                                if (currentGap != null) {
                                                    maxGap = Math.max(maxGap, currentGap);
                                                }
                                                currentGap = 0;
                                
                                            } else if (currentGap != null) {
                                                currentGap++;
                                            }
                                
                                            n = n / 2;
                                        }
                                
                                        return currentGap != null ? Math.max(maxGap, currentGap) : maxGap;
                                    }
                                

                                }

                                【讨论】:

                                  【解决方案22】:

                                  我正在累代码

                                  import java.util.Random;
                                  import java.util.concurrent.ThreadLocalRandom;
                                  
                                  public class Solution {
                                      public int solution(int N) {
                                          // write your code in Java SE 8
                                          int result = 0;
                                          // 먼저 2진수로 변환
                                          String binary = Integer.toBinaryString(N);
                                          // 첫번째 1 위치
                                          int firstOneIdx = 0;
                                          // 다음 1 위치
                                          int nextOneIdx = 0;
                                  
                                          // 전체 loop는 2진수 길이가 최대
                                          for (int i = 0; i <= binary.length(); i++) {
                                  
                                              // 첫번째만 인덱스 체크
                                              if (i == 0) {
                                                  firstOneIdx = binary.indexOf("1");
                                              }
                                  
                                              // 첫번째 인덱스 다음 1 찾기
                                              nextOneIdx = binary.indexOf("1", firstOneIdx + 1);
                                  
                                              // 다음 1이 없으면 loop 나옴
                                              if (nextOneIdx == -1) {
                                                  break;
                                              }
                                  
                                              // 갭
                                              int temp = nextOneIdx - firstOneIdx - 1;
                                  
                                              // 현제 갭이 이전보다 크면 결과 담음
                                              if (temp > result) {
                                                  result = temp;
                                              }
                                  
                                              // 첫번째 인덱스를 이동
                                              firstOneIdx = nextOneIdx;
                                          }
                                  
                                          return result;
                                      }
                                  
                                      public static void main(String[] args) {
                                          Solution solution = new Solution();
                                  
                                          Random random = ThreadLocalRandom.current();
                                  
                                          for (int i = 0; i< 10000; i++){
                                  
                                              int input = random.nextInt(2147483647);
                                              int result = solution.solution(input);
                                  
                                              System.out.println("input = "+input+" result = "+result);
                                          }
                                  
                                      }
                                  }
                                  

                                  【讨论】:

                                    【解决方案23】:

                                    类解决方案{ //Java 解决方案(在 Codility 中 100% 正确)

                                    public int solution(int N) {
                                        // write your code in Java SE 8
                                    
                                        Integer candidate = new Integer(N);
                                        String binStr = candidate.toBinaryString(N);
                                        char[] binArr = binStr.toCharArray();
                                        // System.out.println("Binary String: " + binStr);
                                    
                                        char c, c1;
                                        int counter = 0;
                                    
                                        for (int i = 0; i < binStr.length();) {
                                            // c = binStr.charAt(i);
                                            c = binArr[i];
                                            // System.out.println("c: " + c);
                                            i++;
                                            if (c == '1') {
                                                int tempCounter = 0;
                                                for (int j = 0, k = i; j < binStr.length() - 1; j++, k++) {
                                    
                                                    if (i < binStr.length()) {
                                                        c1 = binArr[i];
                                                    } else {
                                                        break;
                                                    }
                                    
                                                    // System.out.println("c1: " + c1);
                                                    if (c1 == '1') {
                                    
                                                        if (counter < tempCounter)
                                                            counter = tempCounter;
                                    
                                                        break;
                                                    } else {
                                                        // System.out.println("inside counter...");
                                                        tempCounter++;
                                                        i++;
                                                    }
                                                    // i=k;
                                                }
                                            }
                                    
                                        }
                                    
                                        // System.out.println("Counter: " + counter);
                                        return counter;
                                    
                                    }
                                    

                                    }

                                    【讨论】:

                                    • 你应该添加一些你的方法的细节。
                                    【解决方案24】:

                                    这个答案在 coditilty 上进行了测试,它的性能和正确性都达到了 100%。

                                    希望对某人有所帮助。

                                        public static int solution(int N) {
                                        int binaryGap = 0;
                                    
                                        String string = Integer.toBinaryString(N).replaceAll("0+$", "");
                                    
                                        String[] words = string.split("1+");
                                    
                                        Arrays.sort(words);
                                    
                                        if(words.length != 0) {
                                            binaryGap = words[words.length -1].length(); 
                                        }
                                    
                                        return binaryGap;
                                    
                                    }
                                    

                                    【讨论】:

                                    • 欢迎来到 Stack Overflow!请不要只用源代码回答。尝试对您的解决方案如何工作提供一个很好的描述。见:stackoverflow.com/help/how-to-answer。谢谢!
                                    【解决方案25】:

                                    Kotlin 解决方案:

                                    fun binaryGap(number: Int): Int {
                                        return number.toString(2)
                                                .trimEnd { it == '0' }
                                                .split("1")
                                                .map { it.length }
                                                .max() ?: 0
                                    }
                                    

                                    【讨论】:

                                      【解决方案26】:

                                      这是使用 Java 和递归的完美解决方案,满分 100 分。它确实通过了 n = 128 的测试,二进制值为 10100101 和 ans。 2和n = 592,二进制值为1001010000和ans。 2.

                                      class Solution {
                                          public int solution(int n) {
                                              return solution(n, 0, 0, 0);
                                          }
                                      
                                          static int solution(int n, int max, int current, int ones) {
                                              if (n == 0) {
                                                  return max;
                                              } else if (n % 2 == 0) {
                                                  return solution(n / 2, max, ++current, ones);
                                              } else {
                                                  max = ones == 0 ? ones : Math.max(max, current);
                                                  return solution(n / 2, max, 0, ++ones);
                                              }
                                          }
                                      }
                                      

                                      【讨论】:

                                        【解决方案27】:

                                        没有递归的 100% 二进制间隙解决方案

                                        public static int solution(int N) {
                                        
                                        String binary = Integer.toString(N, 2);
                                        int length = binary.length();
                                        int trailingZeros = 0;
                                        
                                        // Get the length of trailing zeros
                                        for (int i = length - 1; i > 0; i--) {
                                        
                                          if (binary.charAt(i) == '0') {
                                            trailingZeros++;
                                          }
                                        
                                          else if (binary.charAt(i) == '1') {
                                            break;
                                          }
                                        }
                                        // length of binary string to consider
                                        int lengthToConsider = length - trailingZeros;
                                        
                                        System.out.println(lengthToConsider);
                                        
                                        int highestGap = 0;
                                        int zeroGapCount = 0;
                                        
                                        for (int i = 1; i < lengthToConsider; i++) {
                                          // Count all subsequent zeros
                                          if (binary.charAt(i) == '0') {
                                            zeroGapCount++;
                                          }
                                        
                                          // else if 1 found then calculate highestGap as below
                                          else if (binary.charAt(i) == '1') {
                                            if (highestGap <= zeroGapCount) {
                                              highestGap = zeroGapCount;
                                            }
                                            // make the zeroGapCount as zero for next loop
                                            zeroGapCount = 0;
                                          }
                                        }
                                        
                                        return highestGap;
                                        
                                        }
                                        

                                        【讨论】:

                                          【解决方案28】:

                                          这是我在 Kotlin 中的解决方案,它在 Codility 上得到了 100% 的好评

                                          fun solution(N: Int): Int {
                                              var binaryGap = 0
                                              val string = Integer.toBinaryString(N).replace("0+$".toRegex(), "")
                                              val words = string.split("1+".toRegex())
                                                                .dropLastWhile { it.isEmpty() }
                                                                .toTypedArray()
                                          
                                              Arrays.sort(words)
                                          
                                              if (words.size.isNotEmpty() {
                                                  binaryGap = words[words.size - 1].length
                                              }
                                          
                                              return binaryGap
                                          

                                          }

                                          【讨论】:

                                            【解决方案29】:

                                            这是我没有递归的解决方案。在 Codability 的应用程序中 100% 测试通过

                                            public class Solution {
                                            
                                                int counter = 0;
                                                Set<Integer> binaryGap = new HashSet<>();
                                                String binaryNumber;
                                            
                                                public int solution(int N) {
                                                    binaryNumber = convert2Binary(N);
                                            
                                                    IntStream.range(1, binaryNumber.length())
                                                            .boxed()
                                                            .forEach(calculateBinaryGapConsumer);
                                            
                                                    return getMaxBinaryGap();
                                                }
                                            
                                                private String convert2Binary(int N) {
                                                    return Integer.toBinaryString(N);
                                                }
                                            
                                                Consumer<Integer> calculateBinaryGapConsumer = i -> {
                                                    char currentChar = binaryNumber.charAt(i);
                                                    char previousChar = binaryNumber.charAt(i-1);
                                                    if (previousChar == '1' && currentChar == '0') {
                                                        increaseCounter();
                                                    } else if (previousChar == '0' && currentChar == '0') {
                                                        increaseCounter();
                                                    } else if (previousChar == '0' && currentChar == '1') {
                                                        saveBinaryGap();
                                                        makeCounterZero();
                                                    }
                                                    //No need to handle case previousChar == '1' && currentChar == '1'.
                                                };
                                            
                                                private void saveBinaryGap() {
                                                    binaryGap.add(counter);
                                                }
                                            
                                                private void increaseCounter() {
                                                    counter++;
                                                }
                                            
                                                private void makeCounterZero() {
                                                    counter = 0;
                                                }
                                            
                                                private int getMaxBinaryGap() {
                                                    return binaryGap.stream().mapToInt(v->v).max().orElse(0);
                                                }
                                            
                                            }
                                            

                                            【讨论】:

                                              【解决方案30】:

                                              使用javascript 不递归

                                              function solution(N) {
                                                var binary = N.toString(2);
                                                var lengths = [];
                                                var length = -1;
                                              
                                                for (var i = 0; i < binary.length; i++) {
                                                    if (
                                                         (binary[i] === 1 && binary[i+1] === 0 && length === -1) 
                                                         || (binary[i] === 0 && length >= 0)
                                                       ) {
                                                          length++;
                                                    }
                                                    else if (binary[i] === 1 && length >= 0) {
                                                        lengths.push(length);
                                                        length = -1;
                                                        i--;
                                                    }
                                                }
                                              
                                                return lengths.length ? Math.max(...lengths) : 0;
                                              }
                                              

                                              【讨论】:

                                                猜你喜欢
                                                • 2016-05-03
                                                • 2014-12-05
                                                • 2016-01-17
                                                • 2019-03-18
                                                • 2021-02-02
                                                • 1970-01-01
                                                • 2015-01-15
                                                • 1970-01-01
                                                • 1970-01-01
                                                相关资源
                                                最近更新 更多