我正在尝试从"/“或"\”将整数转换为字符串生成
例如:6= /\,22 = //\\\\,其中/=1 \=5
对于x=1或x=5是正确的
public String fromArabic(int x)
{
if(x>29 || x<1)
throw new IllegalArgumentException("Error IllegalArgumentException");
int tmp=x;
String out="";
StringBuilder o=new StringBuilder(out);
while(tmp!=0)
{
if(tmp-5>=0)
{
tmp-=5;
o.append("\\");
}
else if(tmp-1>=0 && tmp-5<0)
{
tmp-=1;
o.append("/");
}
}
out=o.toString();
return out;
}产出:
预期:但是是:<\//>
如何使它正确?
发布于 2017-06-13 09:22:29
public String fromArabic(int x)
{
if(x>29 || x<1)
throw new IllegalArgumentException();
int tmp = x;
StringBuilder o = new StringBuilder();
while(tmp != 0)
{
if(tmp >= 5)
{
tmp -= 5;
o.append("\\");
}
else if(tmp >= 1)
{
tmp-=1;
o.append("/");
}
}
return o.reverse().toString();
}发布于 2017-06-13 09:22:17
在tmp == 0和每次迭代减5或1之前不需要循环。
如果将x / 5分配给int,则会得到'\'符号的数目,而x % 5则给出'/'符号的数目。
这里是一行(Java 8)
return String.join("", Collections.nCopies((x%5), "/"), Collections.nCopies((x/5), "\\"));发布于 2017-06-13 09:22:10
您只需在以下情况下反转内部的if序列:
while(tmp!=0)
{
if (tmp-1>=0 && tmp-5<0)
{
tmp-=1;
o.append("/");
}
else if(tmp-5>=0)
{
tmp-=5;
o.append("\\");
}
}https://stackoverflow.com/questions/44517178
复制相似问题