File tree 1 file changed +31
-4
lines changed
src/com/github/jonathanbirkey/chapter05
1 file changed +31
-4
lines changed Original file line number Diff line number Diff line change 2
2
* @author : Jonathan Birkey
3
3
4
4
* @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 .
8
8
*/
9
9
package com .github .jonathanbirkey .chapter05 ;
10
10
11
+ import java .util .Scanner ;
12
+
11
13
public class Exercise37 {
12
14
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
+ }
14
41
}
15
42
}
You can’t perform that action at this time.
0 commit comments