(Java) Write a static method call digitsInARow that takes an integer n as a para
ID: 3765191 • Letter: #
Question
(Java)
Write a static method call digitsInARow that takes an integer n as a parameter and that returns the highest number of digits that appear in a row in the base-10 representation of n. For many numbers the answer will be 1 because they don't have adjacent digits that match. But for a number like 3555585, the answer is 4 because there are four occurance of the digit 5 that appear in a row. You may assume that the integer passes as a parameter to your method is greater than or equal to 0. You may not use String to solve this problem.
Explanation / Answer
/**
* @author Srinivas Palli
*
*/
public class DigitsInARow {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Tests
System.out.println("No of max adjacent 4's in the 2244424:"
+ digitsInARow(2244424));
System.out.println("No of max adjacent 5's in the 3555585:"
+ digitsInARow(3555585));
System.out.println("No of max adjacent 6's in the 3536685:"
+ digitsInARow(3536685));
}
/**
* @param n
* @return the highest number of digits that appear in a row in the base-10
* representation
*/
public static int digitsInARow(int n) {
int maxCount = 0;
int newMaxCount = 0;
while (n != 0) {
// geting current value
int rem = n % 10;
n = n / 10;
int newNo = n;
newMaxCount = 1;
while (newNo != 0) {
// getting next adjacent(newRem)
int newRem = newNo % 10;
// if rem and newRem means (next Adjacent) values are equal
// then increament newMaxCount by 1
if (newRem == rem) {
newMaxCount++;
} else {
break;
}
newNo = newNo / 10;
}
// Checks with old adjacent(maxCount) count and new
// adjacent(newMaxCount) count
// if new adjacent is greater replace the old with new adjacent
// count
// every time maxCount holds the maximum adjacent count
if (maxCount < newMaxCount) {
maxCount = newMaxCount;
}
}// END WHILE
return maxCount;
}
}
OUTPUT:
No of max adjacent 4's in the 2244424:3
No of max adjacent 5's in the 3555585:4
No of max adjacent 6's in the 3536685:2
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.