File tree 2 files changed +35
-10
lines changed
src/com/github/jonathanbirkey/chapter05
2 files changed +35
-10
lines changed Original file line number Diff line number Diff line change @@ -18,25 +18,25 @@ public static void main(String[] args) {
18
18
input .close ();
19
19
20
20
int count = 0 ;
21
- int binary = 0 ;
21
+ int binaryNum = 0 ;
22
22
23
23
while (decimal > 0 ) {
24
24
if (decimal % 2 == 0 ) {
25
- binary += 0 ;
25
+ binaryNum += 0 ;
26
26
} else {
27
- binary += 1 ;
27
+ binaryNum += 1 ;
28
28
}
29
29
decimal = decimal / 2 ;
30
30
if (decimal > 0 ) {
31
- binary = binary * 10 ;
31
+ binaryNum = binaryNum * 10 ;
32
32
}
33
33
34
34
count ++;
35
35
}
36
36
37
37
for (int i = 0 ; i < count ; i ++) {
38
- System .out .printf ("%d" , binary % 10 );
39
- binary = binary / 10 ;
38
+ System .out .printf ("%d" , binaryNum % 10 );
39
+ binaryNum = binaryNum / 10 ;
40
40
}
41
41
}
42
42
}
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 octal ) Write a program that prompts the user to enter a decimal integer and
6
+ * displays its corresponding octal value. Don’t use Java’s Integer.toOctalString(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 Exercise38 {
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 octalNum = 0 ;
22
+
23
+ while (decimal > 0 ) {
24
+ octalNum += decimal % 8 ;
25
+ decimal = decimal / 8 ;
26
+ if (decimal > 0 ) {
27
+ octalNum = octalNum * 10 ;
28
+ }
29
+
30
+ count ++;
31
+ }
32
+
33
+ // 127 = 177
34
+ // 127 ÷ 8 = 15(Quotient) and (7)Remainder
35
+ for (int i = 0 ; i < count ; i ++) {
36
+ System .out .printf ("%d" , octalNum % 10 );
37
+ octalNum = octalNum / 10 ;
38
+ }
14
39
}
15
40
}
You can’t perform that action at this time.
0 commit comments