patterncppModerate
Testing for "bouncy" numbers
Viewed 0 times
bouncynumberstestingfor
Problem
I have a segment of code:
How can I eliminate all of the
/*functions return 4 if all digits are the same, 5 if digits are decreasing, 6 if digits are increasing, 7 if number's digits are bouncy.*/
int variable = 0;
cout << number << endl;
variable = sameDigitsTest(number);
if (variable == 0)
variable = decreasingTest(number);
if (variable == 0)
variable = increasingTest(number);
if (variable == 0)
variable = bouncyTest(number);
/*variable will not be zero any more, hence I do not test for the value zero*/
if (variable == 4 || variable == 5 || variable == 6){
cout << "The number is not bouncy." << endl;
nonBouncyCounter++;
}
if (variable == 7){
cout << "The number is bouncy." << endl;
bouncyCounter++;
}How can I eliminate all of the
if statements to make my code more compact? In fact I was thinking of including a function that includes the functions xTest, and then returning that value and then keeping the two if statements at the end.Solution
The use of magic numbers isn't great. Your
(Note that the latter does actually work with the current
xTest functions should really have Boolean return values, which would allow you to remove the local storage of the result and simplify further (relying on operator short-circuiting):void testNumber(int number) {
if (sameDigitsTest(number) || decreasingTest(number) || increasingTest(number)) {
nonBouncyCounter++;
}
else if (bouncyTest(number)) {
bouncyCounter++;
}
}(Note that the latter does actually work with the current
int return values, but it appears that you've only coded them that way to fit your original implementation; it's unnecessary complexity.)Code Snippets
void testNumber(int number) {
if (sameDigitsTest(number) || decreasingTest(number) || increasingTest(number)) {
nonBouncyCounter++;
}
else if (bouncyTest(number)) {
bouncyCounter++;
}
}Context
StackExchange Code Review Q#74768, answer score: 12
Revisions (0)
No revisions yet.