Get the maximum number of consecutive 1's in n's binary representation - Java Algorithm

Java examples for Algorithm:Number

Description

Get the maximum number of consecutive 1's in n's binary representation

Demo Code

public class Main {

  public static void main(String[] args) {
    int n = 7;//from   www  . java  2  s .c  o  m
    int bin = 0, s = 0, t = 0;

    while (n > 0) {
      bin = n % 2;
      n = n / 2;
      if (bin == 1) {
        s++;
        if (s >= t)
          t = s;
      } else {
        s = 0;
      }
    }

    System.out.println(t);
  }
}

Related Tutorials