Skip to content

Commit 3e1db12

Browse files
finished exercise 38
1 parent 06ab66c commit 3e1db12

File tree

2 files changed

+35
-10
lines changed

2 files changed

+35
-10
lines changed

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

+6-6
Original file line numberDiff line numberDiff line change
@@ -18,25 +18,25 @@ public static void main(String[] args) {
1818
input.close();
1919

2020
int count = 0;
21-
int binary = 0;
21+
int binaryNum = 0;
2222

2323
while (decimal > 0) {
2424
if (decimal % 2 == 0) {
25-
binary += 0;
25+
binaryNum += 0;
2626
} else {
27-
binary += 1;
27+
binaryNum += 1;
2828
}
2929
decimal = decimal / 2;
3030
if (decimal > 0) {
31-
binary = binary * 10;
31+
binaryNum = binaryNum * 10;
3232
}
3333

3434
count++;
3535
}
3636

3737
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;
4040
}
4141
}
4242
}

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

+29-4
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,39 @@
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 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.
88
*/
99
package com.github.jonathanbirkey.chapter05;
1010

11+
import java.util.Scanner;
12+
1113
public class Exercise38 {
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 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+
}
1439
}
1540
}

0 commit comments

Comments
 (0)