Friday 27 May 2016

Hackarank Binary Number - Java Solution

WOW! I solved the second puzzle after 1.5 days of RnD and hard work! Trying all the logic's thinking and patience always pays off!

From yestrday I wn working on this puzzle, may be for some of you it is not that much tricky but for me it was.

Feeling so happy after completing the puzzle at last.


Learn Share n Grow!



Objective
Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given a base- integer, , convert it to binary (base-). Then find and print the base- integer denoting the maximum number of consecutive 's in 's binary representation.
Input Format
A single integer, .
Constraints
Output Format
Print a single base- integer denoting the maximum number of consecutive 's in the binary representation of .
Sample Input 1
5
Sample Output 1
1
Sample Input 2
13
Sample Output 2
2
Solution 1:

package com.number;

import java.util.Scanner;

public class BinaryV2 {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int rem=0,s=0,t=0;


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

            t=s;

        }
        else{

            s=0;
        }   
    }

    System.out.println(t);
}
}

Solution 2:


package com.number;
package com.number;

import java.io.*; 
import java.util.*;
public class Binary {
public static String DecimalToBinary(String binary, int n) {
    if(n == 0) {
        return binary;
    }
    int remainder = n % 2;
    binary = remainder + binary;
    n /= 2;
    return DecimalToBinary(binary, n);
}

public static int count(String binary) {
    int count = 0, max = 0;
    for(int i = 0; i < binary.length(); i++) {
        if(binary.charAt(i) == '1') {
            count++;
            if(count > max)
                max = count;
        }
        else {
            if(count > max)
                max = count;
            count = 0;
        }
    }
    return max;
}
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int decimal = input.nextInt(), total = 0;
    String binary = "";
    binary = DecimalToBinary(binary, decimal);
    total = count(binary);
    System.out.println(total);
}
}


Thanks For being with Us plz Like us On Fb==> computer Stuffs <==

No comments:

Post a Comment

Blog Top Sites

Share Our Badge

 Computer Stuffs

Be Updated Its Free.

Subscribe via Email

Visitors Everyday



Website Security Test

Followers