[英]Java Method: Integer contains 1
I am trying to create a method that will return true if the inputted integer has a one in it, and false if it does not. 我试图创建一个方法,如果输入的整数中有一个,则返回true,否则返回false。 The method works correctly when the inputted number doesn't have a one or ends in a one. 当输入的数字不为1或以1结尾时,该方法可以正常工作。 But if the one is not the last digit in the int, it incorrectly returns false. 但是,如果一个不是int中的最后一位,则它会错误地返回false。 Any ideas whats wrong? 有什么想法怎么了? Here is my script: 这是我的脚本:
public static boolean hasOne(int n) {
boolean retval = false;
if (n % 10 == 1) {
retval = true;
} else {
dropLastDig(n);
}
return retval;
}
public static void dropLastDig(int input) {
int newNum = input/10;
if (newNum > 0) {
hasOne(newNum);
}
}
1000 should return true 1000应该返回true
211 should return true 211应该返回true
1 should return true 1应该返回true
3 should return false 3应该返回false
234 should return false 234应该返回false
只需使用String.valueOf
代替
return String.valueOf(x).contains("1");
You can use recursive function, it's faster: 您可以使用递归函数,它更快:
public static boolean hasOne(int n) {
if(n<0) return hasOne(-n); // check for negatives
if(n==0) return false; // exit condition
if (n % 10 == 1) {
return true;
}
return hasOne(n/10);
}
Or cast it to String, and then check: 或将其强制转换为String,然后检查:
String.valueOf(n).contains("1");
试试String.valueOf(n).contains("1")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.