Skip to content

Commit 06ab66c

Browse files
finished exercise 37, this one was interesting to solve using only loops
1 parent 14340d2 commit 06ab66c

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

src/com/github/jonathanbirkey/chapter05/Exercise37.java

+31-4
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,41 @@
22
* @author : Jonathan Birkey
33
* @mailto : [email protected]
44
* @created : 28Feb2024
5-
* <p>(Display leap years) Write a program that displays all the leap years, 10 per line, from
6-
* 101 to 2100, separated by exactly one space. Also display the number of leap years in this
7-
* period.
5+
* <p>(Decimal to binary) Write a program that prompts the user to enter a decimal integer then
6+
* displays its corresponding binary value. Don’t use Java’s Integer.toBinaryString(int) in this
7+
* program.
88
*/
99
package com.github.jonathanbirkey.chapter05;
1010

11+
import java.util.Scanner;
12+
1113
public class Exercise37 {
1214
public static void main(String[] args) {
13-
// TODO: solve
15+
Scanner input = new Scanner(System.in);
16+
System.out.print("Enter a decimal integer: ");
17+
int decimal = input.nextInt();
18+
input.close();
19+
20+
int count = 0;
21+
int binary = 0;
22+
23+
while (decimal > 0) {
24+
if (decimal % 2 == 0) {
25+
binary += 0;
26+
} else {
27+
binary += 1;
28+
}
29+
decimal = decimal / 2;
30+
if (decimal > 0) {
31+
binary = binary * 10;
32+
}
33+
34+
count++;
35+
}
36+
37+
for (int i = 0; i < count; i++) {
38+
System.out.printf("%d", binary % 10);
39+
binary = binary / 10;
40+
}
1441
}
1542
}

0 commit comments

Comments
 (0)