2017-06-13 143 views
2

我试图转换整数到字符串由 “/” 或 “\”转换整数 “/ ” 串

例如建立: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; 
    } 

OUTPUT:

预期:< [// \\]>但是:< [\\ // //]>

如何使其正确?

+4

为什么请'22 == // \\'? '5 + 5 + 1 + 1 == 12',而不是'22'? –

+0

// \\(12) - 1 + 1 + 5 + 5 – vbv111

回答

1
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(); 
} 
0

你只需要扭转,如果序列里面时:

while(tmp!=0) 
{ 
    if (tmp-1>=0 && tmp-5<0) 
    { 
    tmp-=1; 
    o.append("/"); 
    } 
    else if(tmp-5>=0) 
    {     
    tmp-=5; 
    o.append("\\"); 
    } 
} 
3

没有必要进行循环,直至TMP == 0和每次迭代5。减去或1,如果您分配x/5为int
你得到的'\'符号,数字 和x % 5给你'/'符号

这是一个行数(Java的8)

return String.join("", Collections.nCopies((x%5), "/"), Collections.nCopies((x/5), "\\")); 
0

我建议建立串分为两个阶段:

  1. 将所有1-S
  2. 将所有5-S

技术上我们想要的是x % 5/字符其次是x/5\之一。

像这样的东西(如果我们要不遗余力循环和StringBuilder):

// static: we don't want "this" in the context 
    public static String fromArabic(int x) { 
    if (x > 29 || x < 1) 
     throw new IllegalArgumentException("Error IllegalArgumentException"); 

    // Let's preserve StringBuilder and the loop(s) 
    StringBuilder sb = new StringBuilder(); 

    for (int i = 0; i < x % 5; ++i) 
     sb.append('/'); 

    for (int i = 0; i < x/5; ++i) 
     sb.append('\\'); 

    return sb.toString(); 
    } 

较短的代码是建立直接的字符串:

public static String fromArabic(int x) { 
     if (x > 29 || x < 1) 
      throw new IllegalArgumentException("Error IllegalArgumentException"); 

     char[] chars = new char[x % 5 + x/5]; 
     Arrays.fill(chars, 0, x % 5, '/'); // Ones 
     Arrays.fill(chars, x/5, '\\');  // Fives 

     return new String(chars); 
    } 
0

试试这个:

public static String fromArabic(int x) { 
    if(x > 29 || x < 1) 
     throw new IllegalArgumentException("Error IllegalArgumentException"); 

    StringBuilder out = new StringBuilder(""); 

    int countOf1 = x % 5; 
    int countOf5 = x/5; 

    for (int i = 0; i < countOf1; i++) { 
     out.append("/"); 
    } 

    for (int i = 0; i < countOf5; i++) { 
     out.append("\\"); 
    } 

    return out.toString(); 
}