【问题标题】:Alternate CodingBat sumNumbers exercise solutionAlternate CodingBat sumNumbers 练习解法
【发布时间】:2013-12-16 12:43:50
【问题描述】:

我试图在 Java 的 codingBat 中解决以下问题: http://codingbat.com/prob/p121193

给定一个字符串,返回字符串中出现的数字的总和,忽略所有其他字符。数字是一系列连续的 1 个或多个数字字符。 (注意:Character.isDigit(char) 测试 char 是否是字符 '0'、'1'、.. '9' 之一。Integer.parseInt(string) 将字符串转换为 int。) sumNumbers("abc123xyz") → 123 sumNumbers("aa11b33") → 44 sumNumbers("7 11") → 18

以下是我的解决方案

public int sumNumbers(String str) {
  final int len=str.length();

  int[] numbers=new int[len];
  int count=0;
  String temp="";
  int sum=0;

  for(int i=0;i<len;i++)
  {
     if(Character.isDigit(str.charAt(i)))
     {
        temp=temp+str.substring(i, i+1);

        if(i==len-1)
        {
          numbers[count]=Integer.parseInt(temp);
          break;
         }
        if(Character.isDigit(str.charAt(i+1)))
        {
           continue;
        }
        else
        {
          numbers[count]=Integer.parseInt(temp);
          count++;
          temp="";
        } 
     }   

   }
   for(int j=0;j<numbers.length;j++)
   {
      sum=sum+numbers[j];
    }
    return sum;  

}

这是一个简单的问题,请使用正则表达式或其他任何方式提供任何替代的有效答案,请不要使用集合框架中的任何内容。

【问题讨论】:

  • 好的!!感谢您专注于代码审查部分而不是阅读实际问题......亲爱的先生,我的意思是如果有任何代码爱好者想要审查代码......那么他们可以提供挑剔!
  • 您的问题不属于本站!
  • 提供一个很好的理由,那么为什么堆栈溢出有 [code-review] 标签??
  • 在 [code-review] 标签的标签描述中,您可以通过将鼠标悬停在标签上或点击标签 wiki 来阅读该标签,它显示“代码审查偏离主题在 Stack Overflow,请使用 codereview.stackexchange.com 请求对其他工作代码进行代码审查。”我知道,StackOverflow.com 没有向您显示此消息作为错误消息是愚蠢的,我们在 4 年前就要求提供此功能,但 Jeff Atwood 拒绝了我们此功能。我认为是时候重新审视这个决定了。
  • 好的我已经编辑了问题并删除了标签,请提供并回答!

标签: java string


【解决方案1】:

这是我的解决方案。和你的差不多。

public int sumNumbers(String str) {
    int sPos = -1;
    int ePos = -1;
    int sum = 0;

    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (Character.isDigit(c)) {
            if (sPos < 0) {
                sPos = i;
                ePos = i;
            } else {
                ePos = i;
            }
        } else {
            sum = add(str, sum, sPos, ePos);
            sPos = -1;
        }
    }

    sum = add(str, sum, sPos, ePos);

    return sum;
}

private int add(String str, int sum, int sPos, int ePos) {
    if (sPos >= 0) {
        sum += Integer.parseInt(str.substring(sPos, ePos + 1));
    }
    return sum;
}

【讨论】:

    【解决方案2】:
    public int sumNumbers(String str) {
        int sum = 0;
        StringTokenizer st = new StringTokenizer(str,"$!;Cabcdefghijklmnopqrstuvwxyz ");
        while (st.hasMoreTokens()) {
             sum += Integer.parseInt(st.nextToken());
        }
        return sum;
    }
    

    我很久以前写的,现在想知道我以前写这段代码时的想法。

    【讨论】:

    • 您可以使用正则表达式作为替代解决方案吗?它不会比 stringTokenizer 性能更好吗?我不是在断言只是猜测!
    • 我关心行数。正则表达式或标记器会降低我假设的性能,因此仅基于数组访问 + 循环的解决方案通常应该更快。
    【解决方案3】:

    这是我写的。我不知道它看起来是否更好:)

        public int sumNumbers(String str) {
    String justLetter = "";
    int answer = 0; 
    int number = 0; 
    int factor = 1; 
    
    for (int a = str.length()-1; a >= 0 ; a--) {
    
    justLetter = justLetter + str.charAt(a);
    
    if (Character.isDigit(justLetter.charAt(0))) {
    number = Integer.parseInt(justLetter) * factor; 
    factor = factor * 10; 
    answer = answer + number;
    }
    
    else {
    factor = 1;
    }
    justLetter = "";
    }
    return answer;
    }
    

    【讨论】:

      【解决方案4】:

      这是另一个解决方案:

      public int sumNumbers(String str) {
            if (str.length()<1)
              return 0;
      
            int sum=0;
            int lengthOfDigits;
      
            for (int i=0;i<str.length();i++)
            {
              char currentChar = str.charAt(i);
              lengthOfDigits=1;
              if (Character.isDigit(currentChar))
              {
                  for (int j=i;j<str.length()-1;j++)
                  {
                      char nextChar = str.charAt(j+1);
                      if (Character.isDigit(nextChar))
                          lengthOfDigits++;
                      else
                          break;
                  }   
                  String number = str.substring(i,i+lengthOfDigits);
                  sum+=Integer.parseInt(number);          
      
                  //dont double count, in the case of 123, skip to 3 instead of count 23 again
                  i+=lengthOfDigits;
              }                       
            }
            return sum;
          }
      

      【讨论】:

        【解决方案5】:
        public int sumNumbers(String str) {
            int sum = 0;
            int tmp = 0;
            str = str + " ";
            for (int i = 0; i < str.length(); i++) {
                    if(Character.isDigit(str.charAt(i))){
                        tmp = 0;
                        for(int j = i; j < str.length(); j++){
                            if(!Character.isDigit(str.charAt(j))){
                                tmp = Integer.parseInt(str.substring(i,j));
                                i=j;
                                break;
                            }
                    }   
                        sum += tmp; 
                }
            }
            return sum;
        }
        

        【讨论】:

        • 我对这个练习的解决方案。
        【解决方案6】:

        单循环的替代解决方案:

        public int sumNumbers(String str) {
            boolean b = false;
            String con = null;
            int sum = 0;
            int index = 0;
        
            for (int i = 0; i <= str.length(); i++) {
                if (i < str.length() && Character.isDigit(str.charAt(i))) {
                    if (!b) {
                        index = i;
                        b = true;
                    }
                } else if (b) {
                    con = str.substring(index, i);
                    b = false;
                    sum += Integer.parseInt(con);
                }
            }
            return sum;
        }
        

        【讨论】:

          【解决方案7】:
          public int sumNumbers(String str) {
          
            int sum = 0;
            for(int i = 0 ; i < str.length(); i++ ) {
              if(Character.isDigit(str.charAt(i))) {
                 int count = 0;
                 for (int j = i; j < str.length(); j ++ ) {
                     if (Character.isDigit(str.charAt(j))) {
                        count++;
                     } else {
                        break;
                     }
                 }
                 sum += Integer.parseInt(str.substring(i, i + count));
                 i += count;
              }
            }
          
          
            return sum;
          }
          

          【讨论】:

            【解决方案8】:

            在一个循环中:

            public int sumNumbers(String str) {
            
                int sum=0;
                String temp="";
                str=str+" ";
                for (int i = 0; i < str.length(); i++) {
                    if(Character.isDigit(str.charAt(i))){
                        temp+=str.charAt(i);
                    }else if(temp!=""){
                            sum+=Integer.parseInt(temp);
                            temp="";
                    }
                }
            
                return sum; 
            }
            

            【讨论】:

              【解决方案9】:
              public int sumNumbers(String str) {
              if(str.length()==0){return 0;}
               String [] s = str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
                   int sum = 0;
                   for (int i = 0; i < s.length; i++) {
                      char c = s[i].charAt(0);
                      if(Character.isDigit(c)){
                          sum += Integer.valueOf(s[i]);
                      }
              
                  }
              
                  return sum;
                   }
              

              基于this链接

              【讨论】:

                【解决方案10】:
                    public int sumNumbers(String str) {
                    StringBuilder sb = new StringBuilder(); 
                    int count = 0;
                
                    for (int i = 0; i < str.length(); i++) {
                        if (Character.isDigit(str.charAt(i)) {                           
                            sb.append(str.charAt(i));
                        } else {                             //clear buffer to take next num
                            if (sb.length() != 0) {
                                count += (Integer.parseInt(sb.toString()));
                                sb.setLength(0);
                            }
                        }
                    }
                    if (sb.length() != 0) {
                        count += (Integer.parseInt(sb.toString()));
                    }
                
                    return count;
                    }
                

                【讨论】:

                  【解决方案11】:

                  单个 for 循环中的简单而简短的解决方案:

                     public int sumNumbers(String str) {
                      int sum = 0;
                      String num = "0";
                      for (int i = 0; i < str.length(); i++) {
                          char ch = str.charAt(i);
                          if (Character.isDigit(ch)) {
                              num += ("" + ch);
                          } else {
                              sum += Integer.parseInt(num);
                              num = "0";
                          }
                      }
                      sum += Integer.parseInt(num);
                      return sum;
                  }
                  

                  注意:建议使用StringBuilder.append(),而不是使用+ 连接新字符串。

                  【讨论】:

                  • 这是一个隐藏的宝石,巧妙地使用字符串来保存使用“0”的整数,值得更多的支持
                  【解决方案12】:

                  这就是我的做法。 (我里面有 cmets)。

                  public int sumNumbers(String str) 
                    {
                      //Create a sum for the program.
                      int sum = 0;
                      //Create a blank string
                      String temp = "";
                      //Create a for loop with i iterations, the amount of str.length().
                      for (int i = 0; i < str.length(); i++)
                      {
                        //If we are not on the last iteration,
                        if (i >= 0 && i < str.length() - 1)
                        {
                          //If the current character is a digit,
                          if (Character.isDigit(str.charAt(i)))
                          {
                            //We add the current character to the temporary String
                            temp = temp + str.charAt(i);
                            //If the next character is not a digit, we add the temporary String to the sum.
                            //And wipe out the temporary string so that when we have another number, we can add it.
                            if (!Character.isDigit(str.charAt(i + 1)))
                            {
                              sum = sum + Integer.parseInt(temp);
                              temp = "";
                            }
                          }
                        }
                        //If we are on the last iteration, we do all three without conditions because
                        //We know it ends with the last character in the String.
                        if (i == str.length() - 1)
                        {
                          if (Character.isDigit(str.charAt(i)))
                          {
                            temp = temp + str.charAt(i);
                            sum = sum + Integer.parseInt(temp);
                            temp = "";
                          }
                        }
                      }
                      //We return the sum of the numbers.
                      return sum;
                    }
                  

                  【讨论】:

                    【解决方案13】:
                    Using String builder the performance is slightly improved 
                    
                    
                    public static int sumNumbers(String str) {
                    int sum = 0;
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < str.length(); i++) {
                    char c = str.charAt(i);
                    
                    if (Character.isDigit(c)) {
                    sb.append(c);
                    } else {
                    if (sb.length() > 0) {
                    sum = sum + Integer.parseInt(sb.toString());
                    sb.setLength(0);
                    }
                    }
                    }
                    return sum + Integer.parseInt(sb.toString());
                    }
                    

                    【讨论】:

                    • 您好,欢迎来到 StackOverflow。请格式化您的代码,并在答案中添加一些解释。
                    【解决方案14】:

                    使用单个 for 循环的解决方案。使用字符串生成器的优势将性能提高 20%。

                    public static int sumNumbers(String str) {
                            int sum = 0;
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < str.length(); i++) {
                                char c = str.charAt(i);
                    
                                if (Character.isDigit(c)) {
                                    sb.append(c);
                                } else {
                                    if (sb.length() > 0) {
                                        sum = sum + Integer.parseInt(sb.toString());
                                        sb.setLength(0);
                                    }
                                }
                            }
                            return sum + Integer.parseInt(sb.toString());
                        }
                    

                    【讨论】:

                      【解决方案15】:

                      查看我的代码。

                          public static int sumNumbers(String str) {
                              char[] characters= str.toCharArray();
                              int start=-1,end,sum=0,prev=0;
                              for(int i=0; i<str.length(); i++){
                                  if(i==0) {
                                      if (Character.isDigit(characters[0])) {
                                          start = 0;
                                      }
                                  }else{
                                      if (Character.isDigit(characters[i]) && !Character.isDigit(characters[i-1])) {
                                          start = i;
                                      }
                                      if (!Character.isDigit(characters[i]) && Character.isDigit(characters[i-1])) {
                                          end = i;
                                          if(start>-1){
                                              sum+=Integer.parseInt(str.substring(start,end));
                                          }
                                      }
                                  }
                                  if(i==str.length()-1){
                                      if(start>-1) {
                                          sum += Integer.parseInt(str.substring(start));
                                      }
                                  }
                              }
                              return sum;
                          }
                      

                      【讨论】:

                      【解决方案16】:

                      这是基于另一个我很满意的帖子的解决方案。正在发生的事情是将每个数字附加到 StringBuilder 并为非数字添加一个空格。然后,将所有 double+ 空格替换为单个空格,并从拆分的流中对其进行解析 + 求和..

                      public  int sumNumbers(String str){
                        int len = str.length();
                        StringBuilder nums = new StringBuilder();
                      
                        for(int i=0; i< len; i++){
                            char c = str.charAt(i);
                            if(Character.isDigit(c)) nums.append(c);
                            else nums.append(" ");
                        }
                        String result = nums.toString().trim().replaceAll(" +", " ");
                        return result.equals("") ? 0 : Arrays.stream(result.split(" ")).mapToInt(Integer::parseInt).sum();
                      }
                      

                      【讨论】:

                        【解决方案17】:
                        public int sumNumbers(String str) {
                        int count = 0;
                        int i =0;
                        while(i<str.length()){
                        boolean isDigit = Character.isDigit(str.charAt(i));
                        int j =i;
                        String tote = "";
                        while(isDigit==true&&j<str.length()){
                         if(Character.isDigit(str.charAt(j))==true)
                         {tote += str.charAt(j);
                         j++;}
                         else
                         break;
                        }
                        if(tote.length() > 0)
                        {count += Integer.parseInt(tote);
                        i+=tote.length();}
                        else
                        {i++;}
                        
                        }
                        return count;}
                        

                        这对我来说是最简单的方法!

                        【讨论】:

                          【解决方案18】:

                          这是我的答案

                          public int sumNumbers(String str) {
                            String num = "";
                            int total= 0;
                          
                            for(int i=0;i<str.length();i++){
                          
                              if(Character.isDigit(str.charAt(i))){ // detected a number
                                  int pos = i;
                                  while(pos < str.length() && Character.isDigit(str.charAt(pos))){
                                    pos++; // running the loop until we reach the end of the digits that comprise the number
                          
                                  }
                                    //Now adding the number to the total
                                   total += Integer.parseInt(str.substring(i,pos));  
                                    i = pos; // skipping the position of iterator to past the obtained number 
                              }
                          
                          
                            }
                          
                            return total;//returning result
                          
                          
                          }
                          

                          【讨论】:

                          • 请用正确的评论解释你的回答。
                          • 好吧,在 for 循环中,我首先检测一个 char 是否为数字,然后我为我们的数字 char 前面的字符运行一个 while 循环以获取整数,然后我只需添加获得的数字到总数并跳过循环迭代器(此处为 i)以过去获得数字的位置( i = pos)简单:)
                          【解决方案19】:
                          public static int sumNumbers(String str) {
                                  int result = 0;
                                  StringBuilder sb = new StringBuilder();
                                  if (str.length() < 1) return 0;
                                  for (int i = 0; i < str.length(); i++) {
                                      if (Character.isDigit(str.charAt(i))) {
                                          sb.append(str.charAt(i));
                                      } else {
                                          if (sb.length() > 0) {
                                              result += Integer.parseInt(sb.toString());
                                              sb.delete(0, sb.length());  //we need to clear the stringBuilder to account for new Numbers
                                          }
                                      }
                                  }
                                  if (sb.length() > 0) {
                                      result += Integer.parseInt(sb.toString());
                                  }
                                  return result;
                              }
                          

                          【讨论】:

                            【解决方案20】:

                            我的解决方案

                            public int sumNumbers(String str) {
                            
                                int sum = 0;
                            
                                if (!str.matches(".*\\d.*")) return 0;
                            
                                for (int i = 0; i < str.length(); i++) {
                                    if (!Character.isDigit(str.charAt(i))) {
                                        str = str.replace(str.charAt(i), ' ');
                                    }
                            
                                }
                                str = str.trim();
                            
                                String[] splitStr = str.split("\\s+");
                            
                                for (int z = 0; z < splitStr.length; z++) {
                                    sum += Integer.parseInt(splitStr[z]);
                                }
                            
                                return sum;
                            }
                            

                            【讨论】:

                              【解决方案21】:
                              public int sumNumbers(String str) {
                                    String nums = "";
                                    int sum = 0;
                                    for (int i = 0; i < str.length(); i++){
                                      if (Character.isDigit(str.charAt(i))){
                                        nums += str.charAt(i);
                                        if (i == str.length()-1 && Character.isDigit(str.charAt(i)))
                                          sum += Integer.parseInt(nums);
                                      }
                                      else if (i > 0 && !Character.isDigit(str.charAt(i)) && Character.isDigit(str.charAt(i-1))){
                                        sum += Integer.parseInt(nums);
                                        nums = "";
                                      }
                                    }
                                    return sum;
                                  }
                              

                              【讨论】:

                              • 这使用了一个 for 循环来检查某个索引是否是一个字符,如果是,则将该字符解析为一个整数。由于 Integer.parseInt() 接受一个字符串,我们需要将字符转换为字符串。
                              • 这并不能解决问题。这个答案有几个测试失败。 (codingbat.com/prob/p121193)
                              • @tfmontague 这应该可以解决这个问题
                              【解决方案22】:

                              CodingBat sumNumbers 解决方案

                              • 使用一个 for 循环,避免特殊情况逻辑
                              • 使用整数,避免方法调用
                              public int sumNumbers(String str) {
                                int sum = 0;
                                int num = 0;
                              
                                // If the string is closed,
                                // we don't have to write a special case
                                // to sum in numbers at the end of a string
                                String closedString = str + ".";
                              
                                for (int i = 0; i < closedString.length(); i += 1) {
                                  // Characters are just integers
                                  int c = (int) closedString.charAt(i);
                              
                                  if (c >= '0' && c <= '9') {
                                    // ParseInt alternative
                                    // Decimals are base 10
                                    num = num * 10 + c - '0';
                                  } else {
                                    sum += num;
                                    num = 0;
                                  }
                                }
                              
                                return sum;
                              }
                              

                              或者您还有其他事情要做?

                              public int sumNumbers(String str) {
                                return Arrays
                                  .stream(str.split("\\D+"))
                                  .filter(s -> !s.equals(""))
                                  .mapToInt(Integer::parseInt)
                                  .sum();
                              }
                              

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 2015-03-01
                                • 2014-03-14
                                • 1970-01-01
                                • 2023-03-21
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                相关资源
                                最近更新 更多