-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrange.java
More file actions
69 lines (60 loc) · 1.87 KB
/
range.java
File metadata and controls
69 lines (60 loc) · 1.87 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.Iterator;
import java.util.NoSuchElementException;
class Range implements Iterable<Integer> {
private final int start;
private final int end;
private final int step;
// Constructor for range(start, end, step)
public Range(int start, int end, int step) {
if (step == 0) {
throw new IllegalArgumentException("Step cannot be 0");
}
this.start = start;
this.end = end;
this.step = step;
}
// Overloaded constructor for range(start, end)
public Range(int start, int end) {
this(start, end, 1);
}
// Overloaded constructor for range(end) → (0, end, 1)
public Range(int end) {
this(0, end, 1);
}
// ✅ contains() method
public boolean contains(int number) {
if (step > 0) {
if (number < start || number >= end) return false;
} else {
if (number > start || number <= end) return false;
}
return (number - start) % step == 0;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int current = start;
@Override
public boolean hasNext() {
if (step > 0) {
return current < end; // forward
} else {
return current > end; // backward
}
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int value = current;
current += step;
return value;
}
};
}
@Override
public String toString() {
return "Range(" + start + ", " + end + ", step=" + step + ")";
}
}