[英]I need a function in java where it counts odd or even digits in a specific number and i can choose if i want the the odd or the even digits
举个例子,我有两个号码 JEAN:“5143436111” SAMI:“4501897654”
我需要这个功能来给我这个:
我在 JEAN 号码中有 7 个奇数位 我在 SAMI 号码中有 5 个偶数位
我试过这个 function 但我想选择是否要奇数或偶数 bcz 在这里它显示两者但我希望我的功能给我选择的机会
`
static int countEvenOdd(int n)
{
int even_count = 0;
int odd_count = 0;
while (n > 0)
{
int rem = n % 10;
if (rem % 2 == 0)
even_count++;
else
odd_count++;
n = n / 10;
}
System.out.println ( "Even count : " +
even_`your text`count);
System.out.println ( "Odd count : " +
odd_count);
if (even_count % 2 == 0 &&
odd_count % 2 != 0)
return 1;
else
return 0;
}
`
你可以尝试这样的事情
static final int EVEN = 0;
static final int ODD = 1;
static int count(int n, int remainder)
{
int count = 0;
while (n > 0)
{
int rem = n % 10;
if (rem % 2 == remainder)
count++;
n = n / 10;
}
return count;
}
public static void main(String[] args) {
System.out.println("Even Count: " + count(12233, EVEN));
System.out.println("Odd Count: " + count(12233, ODD));
}
请注意,您实际上只需要计算奇数位或偶数位的个数,因为可以使用输入中的总位数推断出其他计数。 您可以使用:
int countOdd(long n) {
int count = 0;
while (n > 0) {
long rem = n % 10;
if (rem % 2 == 1) ++count;
n = n / 10;
}
return count;
}
long num = 5143436111L;
int odd = countOdd(num);
int even = (int) (Math.log10(num) + 1) - odd;
System.out.println(num + ", EVEN => " + even + ", ODD => " + odd);
这打印:
5143436111, EVEN => 3, ODD => 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.