HackerRank : Day 10: Binary Numbers!
Problem Statement
For this challenge, convert a given number,
Input Format
The first line contains a single integer, T , the number of test cases. The T subsequent lines of test cases each contain a single value, n , the base 10 positive integer to be converted.
Constraints
1≤T≤1000
1≤n≤231
Output Format
For each test case, print the value of n in binary on a new line.
Sample Input
2
4
5
Sample Output
100
101
Explanation
Test Case 0: n=4 evaluates to 1×22+0×21+0×20=1×4+0+0=100 .
Test Case 1:n=5 evaluates to 1×22+0×21+1×20=1×4+0+1×1=101 .
Test Case 1:
public class Solution {
public static void main(String[] args) {
/* Enter your code here.*/
Scanner in=new Scanner(System.in);
int T= in.nextInt();
for(int i=1;i<=T;i++)
{
int n = in.nextInt();
printBinaryform(n);
System.out.println();
}
}
private static void printBinaryform(int n) {
int remainder;
if (n <= 1) {
System.out.print(n);
return; // KICK OUT OF THE RECURSION
}
remainder = n%2;
printBinaryform(n >> 1);
System.out.print(remainder);
}
}
Comments
Post a Comment