-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem07.java
More file actions
44 lines (40 loc) · 1.04 KB
/
Problem07.java
File metadata and controls
44 lines (40 loc) · 1.04 KB
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
import java.util.Scanner;
interface IntSequenceStr{
boolean hasNext();
char next();
}
class BinarySequenceStr implements IntSequenceStr{
private int i; private int j;
private String str = new String();
public BinarySequenceStr(int num) {
for(i = 0; ; i++) { if(num < Math.pow(2, i)){ i--; break; }}
for(j = i; j >= 0; j--) {
if(num >= Math.pow(2,j)) {
str += '1';
num -= Math.pow(2, j); }
else
str += '0'; }
}
public boolean hasNext() {
if(++j <= i ) return true;
else return false;
}
public char next() {
return str.charAt(j);
}
}
public class Problem07 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
String str = in.nextLine();
int num = Integer.parseInt(str);
in.close();
System.out.println("Integer: " + num);
IntSequenceStr seq = new BinarySequenceStr(num);
System.out.print("Binary number: ");
while(seq.hasNext()) System.out.print(seq.next());
System.out.println(" ");
}
}