编写一个名为digitsInARow的静态方法,该方法以整数n作为参数,并返回在n的基数为10的表示形式的行中出现的最大数字位数。对于许多数字来说,答案是1,因为它们没有相匹配的相邻数字。但对于像3555585这样的数字,答案是4,因为出现在一行中的数字5有四次出现。您不允许使用字符串来解决此问题。您可能会认为传递给该方法的值大于或等于0.Java-使用整数
public static int digitsInARow(int n) {
if (n/10 == 0) {
return 1;
}
int count = 0;
int count1 = 0;
while (n > 0) {
int digit = n % 10;
int a = n/10;
if (digit == a % 10) {
count++;
} else {
count1 = Math.max(count1, count);
count = 0;
}
n = n/10;
}
return Math.max(count, count1);
}
我知道if语句已混乱。我试图找出一种方法来比较连续的数字,而不使用Integer类或String类。有什么建议么?
当前代码有什么问题? – Tunaki
您需要跟踪最大计数。现在,只要计数重置为0,您的代码就会忘记它。 – TheGreatContini
@Tunaki输出错误。它一直返回0,除非它是一个单独的数字,我有一个单独的if语句。 –