【问题标题】:Converting from char to int从 char 转换为 int
【发布时间】:2014-11-26 23:48:43
【问题描述】:

我正在尝试对包含整数的字符串应用二进制搜索。这是我的代码

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 转换为 int,我该怎么办? 例如,如何将 '4' 转换为 4?

【问题讨论】:

  • 字符串不包含整数。它们可能包含数字...此外,更重要的是,二分查找仅适用于排序集...
  • @MitchWheat 我提供排序输入
  • 在您的问题中在哪里说明了这一点?无处可去....
  • 对不起,我忘了说我会编辑它

标签: java char int


【解决方案1】:

首先使用Character.forDigit()将您的密钥转换为字符

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
    //...
}

【讨论】:

    【解决方案2】:

    是的,您正在尝试将字符与不起作用的整数进行比较。只使用字符怎么样?

    public static boolean bs(char key,String N){
    

    然后打电话

    bs('5', '25789');
    

    【讨论】:

      【解决方案3】:

      你可以的

      int intValue = N.charAt(mid) - 0x30;
      

      或者

      int intValue = Integer.parseInt(String.valueOf(N.charAt(mid)));
      

      【讨论】:

        猜你喜欢
        • 2014-05-04
        • 2020-04-05
        • 2014-12-27
        • 2017-03-21
        • 2021-11-19
        • 2012-04-28
        • 2012-06-06
        • 2014-09-20
        相关资源
        最近更新 更多