forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecimalToBinary.dart
46 lines (37 loc) · 962 Bytes
/
DecimalToBinary.dart
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
44
45
/*
Conversion of a decimal number to binary form can be achieved by continously dividing the number
number by 2 until the quotient becomes zero. The remained obtained in each step is combined to form
give the resultant binary form of the number
*/
import 'dart:io';
// Function to return binary conversion of number
int toBinary(int num) {
int binary = 0;
int index = 1;
// Iterate till all divisions complete
while (num > 0) {
binary = binary + ( num % 2 * index);
num ~/= 2;
index *= 10;
}
return binary;
}
// Main Function with driver code
void main() {
print("Enter a number :");
int num = int.parse(stdin.readLineSync()!);
// Call binary conversion function
int binary = toBinary(num);
print("Binary conversion of $num is $binary");
}
/**
Space Complexity O(1)
Time Complexity O(n)
Sample input/output:
Enter a number :
13
Binary conversion of 13 is 1101
Enter a number :
25
Binary conversion of 25 is 11001
*/