-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOdometer.cpp
129 lines (105 loc) · 2.36 KB
/
Odometer.cpp
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include<iostream>
using namespace std;
class odometer{
int meterReading;
int length;
public:
odometer(int s){
length = s;
meterReading = getMinReading();
}
odometer(int s, int initialReading){
if(isValidReading(initialReading)){
meterReading = initialReading;
} else {
meterReading = getMinReading();
}
length = s;
}
int nextReading(int meterReading){
if (meterReading == getMaxReading()){
return getMinReading();
}
int nextReading = meterReading + 1;
while (!isValidReading(nextReading)){
nextReading++;
}
meterReading = nextReading;
return meterReading;
}
int previousReading(int meterReading){
if (meterReading == getMinReading()){
cout << "No lesser reading possible" << endl;
return getMinReading();
}
int previousReading = meterReading - 1;
while (!isValidReading(previousReading)){
previousReading--;
}
meterReading = previousReading;
return meterReading;
}
int getMaxReading(){
int maxNumber = 0;
for (int i = 10 - length; i < 10; i++){
maxNumber = maxNumber * 10 + i;
}
return maxNumber;
}
int getMinReading(){
int minNumber = 0;
for (int i = 1; i <= length; i++){
minNumber = minNumber * 10 + i;
}
return minNumber;
}
bool isValidReading(int reading){
int previous, current;
if (readingDigitCount(reading) != length){
return false;
}
current = reading % 10;
while (reading){
reading /= 10;
if (!current){
return false;
}
previous = reading % 10;
if (previous >= current){
return false;
}
current = previous;
}
return true;
}
int readingDigitCount(int n){
int count = 0;
while (n){
n /= 10;
count++;
}
return count;
}
int differenceBetweenReadings(int startingPoint, int endingPoint){
int count = 0;
for (int i = startingPoint; i <= endingPoint; i++){
if (isValidReading(i)){
count++;
}
}
return count;
}
};
int main(){
int odometerSize;
cout << "Enter size of the odometer ";
cin >> odometerSize;
odometer odm(odometerSize);
cout << odm.getMinReading() << endl;
cout << odm.getMaxReading() << endl;
cout << odm.differenceBetweenReadings(1234,5678) << endl;
cout << odm.previousReading(1234) << endl;
cout << odm.nextReading(1234) << endl;
cout << odm.isValidReading(1274) << endl;
return 0;
}