Java 如何写这个s=((n%2)==0?“0”:“1”)和“x2B”;s作为if-else语句?
我在java中有这个方法:Java 如何写这个s=((n%2)==0?“0”:“1”)和“x2B”;s作为if-else语句?,java,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)
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;
}
但似乎不起作用。有人知道为什么吗
如果您有真知灼见,我们将不胜感激 我更愿意,但是代码的问题是附加而不是插入;对于String
连接,我更喜欢StringBuilder
而不是+
。像
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();
}
下面是您的第一个解决方案的详细说明:
// 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;
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));
}
尽管该算法不喜欢负数(在两种解决方案中)
问题是您在错误的位置追加了内容
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;
}
原始表达式以
+s
结尾,因此您应该在if
/else
块中执行此操作,而不是在之后。在赋值之前,必须使用s
的值对+s
进行求值。为什么不返回整数。toBinaryString(n)
?Google什么是三元表达式java
您需要提供程序行为的描述,以及为什么该行为不是正确的或期望的行为。说它不起作用对阅读您的文章的人没有多大帮助。请注意,您应该使用do/while,除非您希望intToBinary(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;
}