Alternate CodingBat sumNumbers运算解决方案

时间:2013-11-30 13:12:42

标签: java string

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

给定一个字符串,返回字符串中出现的数字的总和,忽略所有其他字符。数字是一行中的一个或多个数字字符串。 (注意: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;  

}

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

22 个答案:

答案 0 :(得分:1)

public int sumNumbers(String str) {
    int sum = 0;
    StringTokenizer st = new StringTokenizer(str,"$!;Cabcdefghijklmnopqrstuvwxyz ");
    while (st.hasMoreTokens()) {
         sum += Integer.parseInt(st.nextToken());
    }
    return sum;
}

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

答案 1 :(得分:1)

我写了这个。我不知道它看起来好不好:)

    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;
}

答案 2 :(得分:1)

这是另一种解决方案:

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;
    }

答案 3 :(得分: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;
}

答案 4 :(得分:1)

我的解决方案

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;
}

答案 5 :(得分:1)

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()而不是使用+连接新字符串。

答案 6 :(得分:0)

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

答案 7 :(得分:0)

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;
    }

答案 8 :(得分:0)

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;
    }

答案 9 :(得分:0)

这是我的答案

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


}

答案 10 :(得分:0)

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;}

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

答案 11 :(得分:0)

这是一个基于我感到满意的另一篇文章的解决方案。发生了什么是将每个数字附加到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();
}

答案 12 :(得分:0)

请参阅我的代码。

    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;
    }

答案 13 :(得分:0)

使用单个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());
    }

答案 14 :(得分:0)

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

答案 15 :(得分:0)

这是我如何做到的。 (我在里面有评论)。

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;
  }

答案 16 :(得分:0)

    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;
    }

答案 17 :(得分:0)

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链接

答案 18 :(得分:0)

在一个循环中:

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; 
}

答案 19 :(得分:0)

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;
}

答案 20 :(得分:0)

单循环的替代解决方案:

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;
}

答案 21 :(得分:0)

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;
}