我正在尝试对包含整数的字符串应用二分搜索。这是我的代码
public class abcd {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String num="";
for(int i=0;i<5;i++){
num += input.next();
}
if(bs(5,num))
System.out.println("Yep");
else
System.out.println("Nope");
}
public static boolean bs(int key,String N){
int low=0,high=N.length()-1,mid;
while(high>=low){
mid = (high+low)/2;
if(N.charAt(mid) == key)
return true;
else if(N.charAt(mid) < key)
low = mid+1;
else
high = low-1;
}
return false;
}
}
bs 是二分查找法。我的输入已经排序了。现在我希望查找是否输入了 5,但即使包含 5 作为输入,我总是得到“Nope”作为输出,这意味着 bs 始终返回 false。
我知道 charAt 返回一个 char,这就是问题所在。但是如果我想将该 char 转换为 int,我该怎么办? 例如,如何将“4”转换为 4?
最佳答案
首先使用 Character.forDigit() 将您的 key 转换为字符
public static boolean bs(int intkey,String N){
char key = Character.forDigit(intkey,10);
int low=0,high=N.length()-1,mid;
//...
//the rest of your function should stay the same
//...
}
关于java - 从 char 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27160856/