-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecimalToBinary.java
43 lines (38 loc) · 1.2 KB
/
DecimalToBinary.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Problem
// Result
// Decimal to Binary
// Send Feedback
// Given a decimal number (integer N), convert it into binary and print.
// Note: The given input number could be large, so the corresponding binary number can exceed the integer range. So you may want to take the answer as long for CPP and Java.
// Note for C++ coders: Do not use the inbuilt implementation of "pow" function. The implementation of that function is done for 'double's and it may fail when used for 'int's, 'long's, or 'long long's. Implement your own "pow" function to work for non-float data types.
// Input format :
// Integer N
// Output format :
// Corresponding Binary number (long)
// Constraints :
// 0 <= N <= 10^5
// Sample Input 1 :
// 12
// Sample Output 1 :
// 1100
// Sample Input 2 :
// 7
// Sample Output 2 :
// 111
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long N = s.nextInt();
long ans = 0;
long pow=1;
while (N != 0) {
long rem = N % 2;
ans+=rem*pow;
N = N / 2;
pow*=10;
}
System.out.println(ans);
s.close();
}
}