你怎么写这个s =((n%2)== 0?“ 0”:“ 1”)+ s;作为if-else语句?

时间:2019-11-07 21:00:11

标签: java

我在Java中有此方法:

public static string intToBinary(int n)
{
    string s = "";
    while (n > 0)
    {
        s =  ( (n % 2 ) == 0 ? "0" : "1") +s;
        n = n / 2;
    }
    return s;
}

我想写没有问号的东西。我尝试过:

public static String intToBinary(int n)
    {
        String s = "";
        while (n > 0){
            if ((n%2)==0) {
                s = "0";
            } else {
                s = "1";
            }
           s += s;
           n = n / 2;
        }
        return s;
    }

虽然似乎不起作用。有人知道为什么吗?

我们将不胜感激。

4 个答案:

答案 0 :(得分:2)

我希望使用Integer.toBinaryString(int),但是您代码的问题是附加而不是插入;对于StringBuilder的连接,我也希望+String好。喜欢,

public static String intToBinary(int n) {
    StringBuilder sb = new StringBuilder();
    while (n > 0) {
        if (n % 2 != 0) {
            sb.insert(0, '1'); // s = '1' + s
        } else {
            sb.insert(0, '0'); // s = '0' + s
        }
        n >>= 1; // n /= 2, n = n / 2
    }
    return sb.toString();
}

答案 1 :(得分:0)

以下是您第一个解决方案正在做的事情:

// original
s =  ( (n % 2 ) == 0 ? "0" : "1") +s; 


// 1. ternary operator into local variable
String number = ( (n % 2 ) == 0 ? "0" : "1");   
s =   number + s;


// Ternary Operator as an if else statement
String number;
if ((n % 2 ) == 0) {   
  number = "0";        
}                      
else {                 
  number = "1";        
}                      
s = number + s;

答案 2 :(得分:0)

IntelliJ将您的第一个语句转换为此:

public static String intToBinary(int n) {
    String s = "";
    while (n > 0)
    {
        if ((n % 2) == 0) {
            s = "0" + s;
        } else {
            s = "1" + s;
        }
        n = n / 2;
    }

    return s;
}

我进行了一些基本测试,似乎给出了相同的输出。

public static void main(String[] args) {

    System.out.println(intToBinary(10));
    System.out.println(intToBinary2(10));

    System.out.println(intToBinary(-1));
    System.out.println(intToBinary2(-1));

    System.out.println(intToBinary(1234));
    System.out.println(intToBinary2(1234));
}

尽管该算法不喜欢负数(在两种解决方案中)。

1010 
1010


10011010010 
10011010010

Process finished with exit code 0

答案 3 :(得分:0)

问题在于您要附加的位置错误

public static String intToBinary(int n) {
    String s = "";
    while (n > 0){
        if ((n%2)==0) {
            // You are setting s = "0" here
            s = "0";
            // you need to prepend like this
            s = "0" + s;
        } else {
            // same thing here
            s = "1" + s;
        }
       // now here you have s = "0" + "0" or "1" + "1"
       // s += s;
       n = n / 2;
    }
    return s;
}