In: Computer Science
In java Write a static method named consecutiveDigits that accepts an integer n as a parameter and that returns the highest number of consecutive digits in a row from n that have the same value. For example, the number 3777785 has four consecutive occurrences of the number 7 in a row, so the call consecutiveDigits(3777785) should return 4.
For many numbers the answer will be 1 because they don't have any adjacent digits that match. Below are sample calls on the method. You are not allowed to use a String to solve this problem. You may assume that the value passed to the method is greater than or equal to 0.
consecutiveDigits(99) will return 2
consecutiveDigits(1) will return 1
consecutiveDigits(11335577) will return 2
consecutiveDigits(12345) will return 1
consecutiveDigits(89995) will return 3
Sample output:
The screenshots are attached below for reference.
Please follow them for proper output.
Program to copy:
import java.util.*;
public class Main
{
public static int consecutiveDigits(int n){
String s;
s=Integer.toString(n);
int c=1,temp=1;
for(int i=0;i<s.length()-1;i++){//iterate through all the
numbers
if(s.charAt(i)==s.charAt(i+1)){//check if same or not
temp++;//increment temp if same consecutiveDigits occurs
if(s.length()==2)
return temp;
}
else{
if(c<temp){//check if current count is maximum
c=temp;
temp=1;
}
else
temp=1;
}
}
return c;//return maximum coutn obtained
}
public static void main(String[] args) {
Scanner inp=new
Scanner(System.in);
int num;
String n;
System.out.println("Enter
number:");//read number from user
num=inp.nextInt();
int
res=consecutiveDigits(num);//call the function
System.out.println("The maximum
consecutive same value count is:"+res);//print the returned
value
}
}
Note:
Please let me know in case of any help needed in the comments section.
Plese upvote my answer. Thank you.