给定一个整数,如何检查它是否包含0,使用Java?检查整数以查看其是否包含零
1 = Good 2 = Good ... 9 = Good 10 = BAD! 101 = BAD! 1026 = BAD! 1111 = Good
这怎么办?
给定一个整数,如何检查它是否包含0,使用Java?检查整数以查看其是否包含零
1 = Good 2 = Good ... 9 = Good 10 = BAD! 101 = BAD! 1026 = BAD! 1111 = Good
这怎么办?
你是说如果十进制表示包含0?这样做的绝对简单的方法是:
if (String.valueOf(x).contains("0"))
不要忘记一些不“固有”包含0(除零,当然本身) - 这取决于基础。所以十进制中的“10”是十六进制中的“A”,十进制中的“10”是十六进制中的“16”......在这两种情况下结果都会改变。
可能有更有效的方法来测试整数的十进制表示中是否存在零,但它们可能会涉及上述表达式。
您可以将其转换为字符串,并检查它是否包含字符“0”。
int number = 101;
if(("" + number).contains("0")) {
System.out.println("contains the digit 0");
}
我真的不喜欢将一个值转换为字符串的'“”+ x“方法。它没有明确地表达意图 - 毕竟你并不真正对* concatenation *感兴趣......你在*转换之后*。当然只是MHO。 – 2010-10-02 20:53:33
我承认,这很丑。但它很容易记住。 – tangens 2010-10-02 20:56:56
'String.valueOf()'更难记吗? – whiskeysierra 2010-10-03 09:41:24
Integer.toString(yourIntValue).contains("0");
如果由于某种原因,你不喜欢转换为字符串的解决方案,您可以尝试:
boolean containsZero(int num) {
if(num == 0)
return true;
if(num < 0)
num = -num;
while(num > 0) {
if(num % 10 == 0)
return true;
num /= 10;
}
return false;
}
这也假设num
是基地10
编辑:添加条件来处理负数和0本身。
这是一个例程,它将检测整数中的零。为了使它适用于任何表示形式(十进制,十六进制,八进制,二进制),您需要传入基数作为参数。
public static boolean hasZero(int num, int base) {
assert base > 0 : "must have positive non-zero base";
if (num == 0)
return true;
while(num != 0) {
if (num % base == 0) {
return true;
}
else {
num = num/base;
}
}
return false;
}
public static void main(String args[]) {
System.out.println(hasZero(10, 10)); // true (base 10 int)
System.out.println(hasZero(-12, 10)); // false (base 10 int)
System.out.println(hasZero(0x10, 16)); // true (hex is base 16)
System.out.println(hasZero(0x1A, 16)); // false (hex is base 16)
}
几乎duplacate到上面的答案 – Younes 2010-10-04 13:51:55
我不知道这是否容易,但这是另一种方式。 将数字拆分为一个整数数组。然后分类并检查第一个元素是否为零。 E.g
int n = 14501;
// after splitting
int na = {1, 4, 5, 0, 1};
// after sorting
int na = {0, 1, 1, 4, 5};
你能告诉你如何从'n'到'na'吗? – whiskeysierra 2010-10-03 09:40:15
不使用Java,但它并不完全难以从C++ PS转换。对使用字符串转换的任
bool Contains0InBase10(unsigned int i, unsigned int& next)
{
unsigned int divisor = 10;
unsigned int remainder = 0;
while(divisor <= i)
{
unsigned int newRemainder = i%divisor;
if(newRemainder - remainder == 0)
{
// give back information allowing a program to skip closer to the next
// number that doesn't contain 0
next = i + (divisor/10) - remainder;
return true;
}
divisor *= 10;
remainder = newRemainder;
}
return false;
}
尽管这个算法本来可以比字符串转换更有效率,但为什么模数运算符将会执行OP要查找的内容的一点说明可能会澄清您的帖子。 – Sean 2010-10-03 02:31:55
+1 - 我会在生产代码中使用此解决方案,直到有人向我证明a)这是一个瓶颈,并且b)另一个解决方案明显更快。简单性和可读性有很多要说的。 – 2010-10-02 21:05:45
感谢您的回答,运作良好。 – 2010-10-02 21:11:46