在Java中计算整数中的偶数
我试图用Java编写一个方法,如果一个整数只包含偶数,它将返回true
例如,当输入整数为2468时,该方法将返回true。 另一个例子是,如果输入整数为-68,则该方法将返回true。如果整数由24638组成,则该方法应返回false
我也尝试只使用整数。我不想使用ToString()将整数的长度作为循环中的条件,也不想使用数组
我搜索了论坛,但大多数回复似乎都使用了ToString()或我正在避免使用的数组。 我的代码如下:
int countEven = 0;
int countOdd = 0;
if (n == 0)
countEven++;
while (n != 0) {
int lastdigit = n % 10;
if (lastdigit == 0 || lastdigit % 2 == 0)
countEven++;
else
countOdd++;
n = n /10;
}
if (countEven >= 0); return true;
# 1 楼答案
您没有检查
countodd
的条件。假设数字是235。你的counteven
将是1,countodd
将是2。然后,不管发生什么,最后一个if条件都将返回true
。试试这个# 2 楼答案
问题是你最后的if语句不正确
试试这个: