Interview Question


Country: United States




Comment hidden because of low score. Click to expand.
7
of 7 vote

package com.algorithm.amazon;

public class SumDigits {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			String s = "1a3sdf4a5fggt";
			char[] arr = s.toCharArray();
			int sum = 0;
			String localDigit="";
			for (int i = 0; i < arr.length; i++) {
				
				if (Character.isDigit(arr[i])) {
					localDigit=localDigit+arr[i];
					
				}
				else
				{
					if(localDigit!="")
						sum = sum + Integer.parseInt(String.valueOf(localDigit));
					localDigit="";
				}
			}
			System.out.println(sum);
		}

	
}

- Vir Pratap Uttam April 12, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String s = "123sdf45fggt";
		char[] arr = s.toCharArray();
		int sum = 0;
		for (int i = 0; i < arr.length; i++) {
			if (Character.isDigit(arr[i])) {
				sum = sum + Integer.parseInt(String.valueOf(arr[i]));
			}
		}
		System.out.println(sum);
	}

- Brock Lesnar March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

This is wrong. You are adding 1+2+3+4+5. The answer is supposed to be
123 + 45

- Alex March 31, 2015 | Flag
Comment hidden because of low score. Click to expand.
7
of 7 votes

package com.algorithm.amazon;

public class SumDigits {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			String s = "1a3sdf4a5fggt";
			char[] arr = s.toCharArray();
			int sum = 0;
			String localDigit="";
			for (int i = 0; i < arr.length; i++) {
				
				if (Character.isDigit(arr[i])) {
					localDigit=localDigit+arr[i];
					
				}
				else
				{
					if(localDigit!="")
						sum = sum + Integer.parseInt(String.valueOf(localDigit));
					localDigit="";
				}
			}
			System.out.println(sum);
		}

	
}

- Vir Pratap Uttam April 12, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void printSum(string s)
{
	string sNum = "";
	int sum= 0;
	vector<int> v;

	for(int i=0;i<s.length();i++)
	{
		if(isdigit(s[i]))
		{
			sNum += s[i];
		}else if(sNum.length() > 0)
		{
			sum += atoi(sNum.c_str());
			sNum = "";
		}
	}

	if(sNum.length() > 0)
		sum += atoi(sNum.c_str());

	printf("\nsum = %d",sum);
}

- Alex March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String s = "7 13";
		char[] arr = s.toCharArray();
		int total = 0;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			if (Character.isDigit(arr[i])) {
				sb.append(arr[i]);
			} else {
				if (!sb.toString().isEmpty())
					total = total + Integer.parseInt(sb.toString());
				sb = new StringBuilder();
			}
		}
		if (!sb.toString().isEmpty())
			total = total + Integer.parseInt(sb.toString());
		System.out.println(total);

- ak47 March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use a reg expression like "\\d" and atoi and add all numbers.

- kingKode March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class SumOfDigitsInAlphanumeric {

public static void main(String[] args) {
String s = "123sdf45fggt10jj98";
s = s + 'a';
char[] ch = s.toCharArray();
int res = 0;
int value = 0;
for (char c : ch) {
int i = c - '0';
if (i <= 9) {
value = value * 10 + i;
continue;
}
res = res + value;
value = 0;
}
System.out.println("res " + res);
}

}

- Naveen March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class SumOfDigitsInAlphanumeric {

public static void main(String[] args) {
String s = "123sdf45fggt10jj98";
s = s + 'a';
char[] ch = s.toCharArray();
int res = 0;
int value = 0;
for (char c : ch) {
int i = c - '0';
if (i <= 9) {
value = value * 10 + i;
continue;
}
res = res + value;
value = 0;
}
System.out.println("res " + res);
}

}

- Naveen March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assumes that the string uses ASCII characters.

public static int sumContainedInts(String str){
  int sum = 0;
  int val = 0;
  for(int i = 0; i < str.length(); i++){
    char c = str.getChar(i);
    int dig = digVal(c);
    if(dig > -1){
      val *= 10;
      val += dig;
    }
    else{
      sum += val;
      val = 0;
    }
  }
  sum += val;
  return sum;
}

private static int digVal(char c){
  int val = (int)c - (int)'0';
  if(val > 9){
    val = -1;
  }
  return val;
}

- a nony mouse March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package random;

public class IntFinderAndAdder {
	
	private int myIntParser(String str){
		int retNum = 0;
		if(str == null)
			return 0;
		else {
			for (int i = 0 ; i < str.length(); i++){
			retNum = 10 * retNum;
			retNum = retNum + str.charAt(i) -'0';
			}
		return retNum;
		}
	}
	
	
	public int getSumFromGarbageString(String str){
		String numStr = new String();
		int totalSum = 0;
		if (str == null || str.length() == 0){
			System.out.println("empty string ");
			return 0;
		}
		else {
			boolean numFlag = false;
			for (int i = 0; i < str.length(); i ++){
					if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){
						numFlag = true;
						numStr = numStr + str.charAt(i);
					}
					else {
						numFlag = false;
						totalSum = totalSum + myIntParser(numStr);
						numStr ="";//blank out the older number
					}
			}
		return totalSum;
		}
	}
	
	

	public static void main(String[] args) {
		IntFinderAndAdder demo = new IntFinderAndAdder();
		
		System.out.println(demo.getSumFromGarbageString("abdf12bg3bh5j"));
	}
}

- Partha March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package random;

public class IntFinderAndAdder {
	
	private int myIntParser(String str){
		int retNum = 0;
		if(str == null)
			return 0;
		else {
			for (int i = 0 ; i < str.length(); i++){
			retNum = 10 * retNum;
			retNum = retNum + str.charAt(i) -'0';
			}
		return retNum;
		}
	}
	
	
	public int getSumFromGarbageString(String str){
		String numStr = new String();
		int totalSum = 0;
		if (str == null || str.length() == 0){
			System.out.println("empty string ");
			return 0;
		}
		else {
			boolean numFlag = false;
			for (int i = 0; i < str.length(); i ++){
					if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){
						numFlag = true;
						numStr = numStr + str.charAt(i);
					}
					else {
						numFlag = false;
						totalSum = totalSum + myIntParser(numStr);
						numStr ="";//blank out the older number
					}
			}
		return totalSum;
		}
	}
	
	

	public static void main(String[] args) {
		IntFinderAndAdder demo = new IntFinderAndAdder();
		
		System.out.println(demo.getSumFromGarbageString("abdf12bg3bh5j"));
	}
}

- Partha March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package random;

public class IntFinderAndAdder {
	
	private int myIntParser(String str){
		int retNum = 0;
		if(str == null)
			return 0;
		else {
			for (int i = 0 ; i < str.length(); i++){
			retNum = 10 * retNum;
			retNum = retNum + str.charAt(i) -'0';
			}
		return retNum;
		}
	}
	
	
	public int getSumFromGarbageString(String str){
		String numStr = new String();
		int totalSum = 0;
		if (str == null || str.length() == 0){
			System.out.println("empty string ");
			return 0;
		}
		else {
			boolean numFlag = false;
			for (int i = 0; i < str.length(); i ++){
					if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){
						numFlag = true;
						numStr = numStr + str.charAt(i);
					}
					else {
						numFlag = false;
						totalSum = totalSum + myIntParser(numStr);
						numStr ="";//blank out the older number
					}
			}
		return totalSum;
		}
	}
	
	

	public static void main(String[] args) {
		IntFinderAndAdder demo = new IntFinderAndAdder();
		
		System.out.println(demo.getSumFromGarbageString("abdf12bg3bh5j"));
	}
}

- Partha Maitra March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package random;

public class IntFinderAndAdder {

private int myIntParser(String str){
int retNum = 0;
if(str == null)
return 0;
else {
for (int i = 0 ; i < str.length(); i++){
retNum = 10 * retNum;
retNum = retNum + str.charAt(i) -'0';
}
return retNum;
}
}


public int getSumFromGarbageString(String str){
String numStr = new String();
int totalSum = 0;
if (str == null || str.length() == 0){
System.out.println("empty string ");
return 0;
}
else {
boolean numFlag = false;
for (int i = 0; i < str.length(); i ++){
if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){
numFlag = true;
numStr = numStr + str.charAt(i);
}
else {
numFlag = false;
totalSum = totalSum + myIntParser(numStr);
numStr ="";//blank out the older number
}
}
return totalSum;
}
}



public static void main(String[] args) {
IntFinderAndAdder demo = new IntFinderAndAdder();

System.out.println(demo.getSumFromGarbageString("abdf12bg3bh5j"));
}
}

- Anonymous March 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.regex.*;
import java.util.*;

class Test {

public static void main(String[] args) {

String str = "asdf12bgt3bh5j";
int sum = findandAdd(str);
System.out.println("sum: " + sum);
}
public static int findandAdd(String str) {

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
int sum = 0;
while(matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
return sum;
}
}

- Harris April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
String input="123sdf45fggt";
String s="";
String[] values;
int sum=0;
char[] chararray=input.toCharArray();
for (int i=0;i<chararray.length;i++){
if(Character.isDigit(chararray[i])){
s+=chararray[i];
if(Character.isAlphabetic(chararray[i+1])){
s+=" , ";
}
}
}
values=s.split(" , ");
for(String i:values){
sum+=Integer.parseInt(i);
}
System.out.println(sum);
}

- Anonymous April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
String input="123sdf45fggt";
String s="";
String[] values;
int sum=0;
char[] chararray=input.toCharArray();
for (int i=0;i<chararray.length;i++){
if(Character.isDigit(chararray[i])){
s+=chararray[i];
if(Character.isAlphabetic(chararray[i+1])){
s+=" , ";
}
}
}
values=s.split(" , ");
for(String i:values){
sum+=Integer.parseInt(i);
}
System.out.println(sum);
}

- Anonymous April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

\\\ public static void main(String[] args) {
String input="123sdf45fggt";
String s="";
int sum=0;
char[] chararray=input.toCharArray();
for (int i=0;i<chararray.length;i++){
if(Character.isDigit(chararray[i])){
s+=chararray[i];
if(Character.isAlphabetic(chararray[i+1])){
sum+=Integer.parseInt(s);
s="";
}
}
}
System.out.println(sum);
}///

- Anonymous April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

\\\ public static void main(String[] args) {
String input="123sdf45fggt";
String s="";
int sum=0;
char[] chararray=input.toCharArray();
for (int i=0;i<chararray.length;i++){
if(Character.isDigit(chararray[i])){
s+=chararray[i];
if(Character.isAlphabetic(chararray[i+1])){
sum+=Integer.parseInt(s);
s="";
}
}
}
System.out.println(sum);
}///

- Anonymous April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String input="123sdf45fggt";
		String s="";
		int sum=0;
		char[] chararray=input.toCharArray();
		for (int i=0;i<chararray.length;i++){
			if(Character.isDigit(chararray[i])){
				s+=chararray[i];
				if(Character.isAlphabetic(chararray[i+1])){
					sum+=Integer.parseInt(s);
					s="";
				}				
			}	
		}		
		System.out.println(sum);
	}

- Shinto April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

public static void main(String[] args) {
String input="careercup23ja3va43";
String s="";
int sum=0;
char[] chararray=input.toCharArray();
for (int i=0;i<=chararray.length-1;i++){
if(Character.isDigit(chararray[i])){
s+=chararray[i];
if(i == chararray.length-1){
sum+=Integer.parseInt(s);
s="";
}else
if( Character.isAlphabetic(chararray[i+1])){
sum+=Integer.parseInt(s);
s="";
}
}
}
System.out.println(sum);
}

- Naga Sudhakar April 17, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String input="123sdf45fggt";
		String s="";
		int sum=0;
		char[] chararray=input.toCharArray();
		for (int i=0;i<chararray.length;i++){
			if(Character.isDigit(chararray[i])){
				s+=chararray[i];
				if(Character.isAlphabetic(chararray[i+1])){
					sum+=Integer.parseInt(s);
					s="";
				}				
			}	
		}		
		System.out.println(sum);
	}

- Shinto April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String input="123sdf45fggt";
		String s="";
		int sum=0;
		char[] chararray=input.toCharArray();
		for (int i=0;i<chararray.length;i++){
			if(Character.isDigit(chararray[i])){
				s+=chararray[i];
				if(Character.isAlphabetic(chararray[i+1])){
					sum+=Integer.parseInt(s);
					s="";
				}				
			}	
		}		
		System.out.println(sum);
	}

- Shinto April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String input="123sdf45fggt";
		String s="";
		int sum=0;
		char[] chararray=input.toCharArray();
		for (int i=0;i<chararray.length;i++){
			if(Character.isDigit(chararray[i])){
				s+=chararray[i];
				if(Character.isAlphabetic(chararray[i+1])){
					sum+=Integer.parseInt(s);
					s="";
				}				
			}	
		}		
		System.out.println(sum);
	}

- Shinto April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void addDigitsInStr(char strArr[SIZE])
{
	int iCnt=0,j=0,iTmp=0;
	char temp[SIZE];
	strcpy(temp,"");
	for(int i=0;strArr[i]!='\0';i++)
	{
		iTmp =strArr[i]-'0';
		if(iTmp>=0 && iTmp<=9)
		{
			temp[j] = strArr[i];
			j++;
			if(strArr[i+1]!='\0')
			continue;
		}
		temp[j]='\0';
		if(strcmp(temp,"")!=0)
		{
			iCnt = iCnt + atoi(temp);
			strcpy(temp,"");
			j=0;
		}
	}
}

- sv April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Three solutions

public static int sum_1(String data) {
		java.util.regex.Pattern p = java.util.regex.Pattern.compile("[0-9]+");
		java.util.regex.Matcher m = p.matcher(data);
		int sum = 0;
		while(m.find()) {
			sum += Integer.parseInt(m.group());
		}
		
		return sum;
	}
	
	public static int sum_2(String data) {
		boolean inNumber = false;
		int sum = 0;
		int start = 0;
		for(int i = 0; i < data.length(); ++i) {
			if(Character.isDigit(data.charAt(i))) {
				if(!inNumber) {
					start = i;
					inNumber = true;
				}
			} else {
				if(inNumber) {
					sum += Integer.parseInt(data.substring(start, i));
					inNumber = false;
				}
			}
		}
		if(inNumber)
			sum += Integer.parseInt(data.substring(start));
		return sum;
	}
	
	public static int sum_3(String data) {
		int sum = 0;
		int num = 0;
		for(char c : data.toCharArray()) {
			switch(c) {
			case '0': num *= 10; break;
			case '1': num *= 10; num += 1; break;
			case '2': num *= 10; num += 2; break;
			case '3': num *= 10; num += 3; break;
			case '4': num *= 10; num += 4; break;
			case '5': num *= 10; num += 5; break;
			case '6': num *= 10; num += 6; break;
			case '7': num *= 10; num += 7; break;
			case '8': num *= 10; num += 8; break;
			case '9': num *= 10; num += 9; break;
			default:
				sum += num;
				num = 0;
				break;
			}
		}
		sum += num;
		return sum;
	}

- hideki.ikeda April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This problem can test either of two skills: Understanding the language you use/regular expressions and the usage of existing resources, or simply how to create a way to scan the string, pick out the numbers, and add them from scratch.

The first method is really quite simple, most languages have support for regex operations, such as python's re library. Use the regular expression "[0-9]+" with the findall function in the re library and then iterate through, adding as you go to a sum.

In python:

import re

def find_sum(s):
	parsed_list = re.findall(r'[0-9]+',s)
	sum = 0
	for val in parsed_list:
		sum += int(val)
	return sum

For interviews, this is a mixed bag, as the interviewer will either see this as smart and effectively using a helpful technology, or they will think you are being lazy and don't know how to implement the manual solution.

Admittedly, the manual solution is a pain in the rear, or at least it seems that way when you know you can use a regex (please, if you do the manual method, afterwards mention that it could be done in less lines with use of regex, just to get some points for knowing practical tech). For the manual solution, the process looks more like:

def find_sum(s):
    start_pt = 0
    tracking = False
    sum = 0
    for i in range(0,len(s)):
        converted_val = ord(s[i]) - 48
        if converted_val <= 9 and converted_val >= 0:
            if not tracking:
                start_pt = i
                tracking = True
        else:
            if tracking:
                sum += convert_to_int(s[start_pt:i])
                tracking = False
    sum += convert_to_int(s[start_pt:]) if tracking else 0
    return sum

def convert_to_int(val):
    sum = 0
    for i in range(0,len(val)):
	    sum += (10**(len(val) - 1 - i))*(ord(val[i])-48)
    return sum

the logic here is that initially you are not assessing a group of values, if you see one which when converted through ascii values is actually a decimal unit (0-9) you set the starting pointer to that index, and flag that you are tracking a group. When you run into a non-decimal, you run the substring from the start pointer to the last valid value you saw through basic conversion from separate digits to a whole int. Then add it to the sum, and set the tracking flag to false to indicate that the start pointer should be moved next time you see a valid digit.

a bit messy and not quite what i would say is truly from scratch (i did utilize the ord conversion, but as most languages can convert a char to its ascii value, its fair game) but it will get the job done in O(2n) => O(n) time, since it only runs through the array once, and the only other iterations are done in conversion, worst case, the entire string is one int value and it must be iterated through twice. It also has O(1) space usage, since you are only using ints and booleans to track the values.

- Javeed April 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class adddigit
{

public static void main(String arg[]) throws IOException
{
int total=0;

String v="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
for(int i=0;i<s.length();i++)
{
int asci=(int)s.charAt(i);

if(asci>47 && asci<58)
{

v=v+s.charAt(i);


if(i==(s.length()-1)){total=total+Integer.parseInt(v);}
}
else
{
if(!v.equals("")){
total=total+Integer.parseInt(v);
v="";
}

}
}
System.out.println("Total Value:"+total);
}
}

- Ganapathi April 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{ { {public class adddigit
{

public static void main(String arg[]) throws IOException
{
int total=0;

String v="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
for(int i=0;i<s.length();i++)
{
int asci=(int)s.charAt(i);

if(asci>47 && asci<58)
{

v=v+s.charAt(i);


if(i==(s.length()-1)){total=total+Integer.parseInt(v);}
}
else
{
if(!v.equals("")){
total=total+Integer.parseInt(v);
v="";
}

}
}
System.out.println("Total Value:"+total);
}
}

} } }

- ganapathi April 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def theCorrectWayToSumDigitsIn(someText):
numbers = [0]
total=0
isPrevNum=False
for x in list(someText):
if str.isdigit(x):
if isPrevNum:
numbers[len(numbers)-1]= numbers[len(numbers)-1]*10 + int(x)
else:
isPrevNum=True
numbers.append(int(x))
else:
isPrevNum = False
for number in numbers:
total = total + number
print 'total:',total

- ss April 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{
def theCorrectWayToSumDigitsIn(someText):
numbers = [0]
total=0
isPrevNum=False
for x in list(someText):
if str.isdigit(x):
if isPrevNum:
numbers[len(numbers)-1]= numbers[len(numbers)-1]*10 + int(x)
else:
isPrevNum=True
numbers.append(int(x))
else:
isPrevNum = False
for number in numbers:
total = total + number
print 'total:',total
}

- ss April 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class intFinderAndAdder {


public static void checkSum(String str) {
char[] chArray = str.toCharArray();
int sum=0,temp;
for(int i=0;i<chArray.length;i++)
{
//System.out.println(chArray[i]);
if(Character.isDigit(chArray[i]))
{
temp=0;
do {
//System.out.println(chArray[i]);
temp=temp*10+(int)(chArray[i]-'0');

i++;
}while(Character.isDigit(chArray[i]));
sum=sum+temp;
}

}
System.out.println(sum+ " is a sum of the digits");
}
public static void main(String[] argv)
{
String str="123abc10c";
checkSum(str);
}
}

- Harjit Singh April 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{
public class intFinderAndAdder {


public static void checkSum(String str) {
char[] chArray = str.toCharArray();
int sum=0,temp;
for(int i=0;i<chArray.length;i++)
{
//System.out.println(chArray[i]);
if(Character.isDigit(chArray[i]))
{
temp=0;
do {
//System.out.println(chArray[i]);
temp=temp*10+(int)(chArray[i]-'0');

i++;
}while(Character.isDigit(chArray[i]));
sum=sum+temp;
}

}
System.out.println(sum+ " is a sum of the digits");
}
public static void main(String[] argv)
{
String str="123abc10c";
checkSum(str);
}
}

}}

- Harjit Singh April 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class intFinderAndAdder {

	
	public static void checkSum(String str) {
		char[] chArray = str.toCharArray();
		int sum=0,temp;
		for(int i=0;i<chArray.length;i++)
		{
			//System.out.println(chArray[i]);
			if(Character.isDigit(chArray[i]))
			{
				temp=0;
				do {
					//System.out.println(chArray[i]);
					temp=temp*10+(int)(chArray[i]-'0');
					
					i++;
				}while(Character.isDigit(chArray[i]));
				sum=sum+temp;
			}
				
		}
		System.out.println(sum+ " is a sum of the digits");
	}
	public static void main(String[] argv)
	{
		String str="123abc10c";
		checkSum(str);
	}
}

- Harjit Singh April 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class intFinderAndAdder {

	
	public static void checkSum(String str) {
		char[] chArray = str.toCharArray();
		int sum=0,temp;
		for(int i=0;i<chArray.length;i++)
		{
			//System.out.println(chArray[i]);
			if(Character.isDigit(chArray[i]))
			{
				temp=0;
				do {
					//System.out.println(chArray[i]);
					temp=temp*10+(int)(chArray[i]-'0');
					
					i++;
				}while(Character.isDigit(chArray[i]));
				sum=sum+temp;
			}
				
		}
		System.out.println(sum+ " is a sum of the digits");
	}
	public static void main(String[] argv)
	{
		String str="123abc10c";
		checkSum(str);
	}

}

- Harjit Singh April 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class intFinderAndAdder {

	
	public static void checkSum(String str) {
		char[] chArray = str.toCharArray();
		int sum=0,temp;
		for(int i=0;i<chArray.length;i++)
		{
			//System.out.println(chArray[i]);
			if(Character.isDigit(chArray[i]))
			{
				temp=0;
				do {
					//System.out.println(chArray[i]);
					temp=temp*10+(int)(chArray[i]-'0');
					
					i++;
				}while(Character.isDigit(chArray[i]));
				sum=sum+temp;
			}
				
		}
		System.out.println(sum+ " is a sum of the digits");
	}
	public static void main(String[] argv)
	{
		String str="123abc10c";
		checkSum(str);
	}
}

- Harjit Singh April 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string:");
String s1 = scan.nextLine();
int num, sum = 0;
char[] c1 = s1.toCharArray();
for(int i = 0; i < c1.length; i++)
{
if(Character.isLetter(c1[i]))
{
continue;
}
if(Character.isDigit(c1[i]))
{
num = (int)(c1[i] - '0');
while(i++ < c1.length && Character.isDigit(c1[i])){
num = num * 10 + (c1[i] - '0');
}
System.out.println("Number: " + num);
sum += num;
}
}
System.out.println("Sum :" + sum);
}

- Anonymous April 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String args[]){
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a string:");
      String s1 = scan.nextLine();
      int num, sum = 0;
      char[] c1 = s1.toCharArray();
      for(int i = 0; i < c1.length; i++)
      {
         if(Character.isLetter(c1[i]))
         {         
            continue;
         }
         if(Character.isDigit(c1[i]))
         {
            num = (int)(c1[i] - '0');
            while(i++ < c1.length && Character.isDigit(c1[i])){
               num = num * 10 + (c1[i] - '0');
            }
            System.out.println("Number: " + num);
            sum += num;
         }
      }
      System.out.println("Sum :" + sum);
   }

- Anonymous April 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int getSum(String input) {
        int result = 0;
        String prev="";
        for (char ch : input.toCharArray()) {
            if (Character.isDigit(ch)) {
                if (prev.isEmpty()) {
                    prev = String.valueOf(ch);
                } else {
                    prev += String.valueOf(ch);
                }
            } else {
                if (!prev.isEmpty()) {
                    result += Integer.valueOf(prev);
                    prev = "";
                }
            }
        }
        if (!prev.isEmpty()) {
            result += Integer.valueOf(prev);
            prev = "";
        }
        return result;
    }

- psisanon April 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int digitSum(String str){
		if(null == str ) throw new IllegalArgumentException("");
		if("".equals(str.trim())) throw new IllegalArgumentException("");
		
		
		int sum = 0;		
		int tracker = 0;
		StringBuilder charBuffer = new StringBuilder();
		for(int i=0;i<str.length();i++){
			if(Character.isDigit(str.charAt(i))){
				tracker = i;
				charBuffer.append(str.charAt(i));
				while(++tracker < str.length() && Character.isDigit(str.charAt(tracker))){
					charBuffer.append(str.charAt(tracker));	
					i = tracker;
				}
				sum += Integer.parseInt(charBuffer.toString());
				charBuffer = new StringBuilder();
			}
		}		
		return sum;
	}

- Aditya April 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String s = "abc12fds3dsf7";
		int result = 0;
		StringBuilder temp = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if(Character.isDigit(c)) {
				temp.append(c);
			}
			else {
				if(temp.length() > 0) {
					result += Integer.parseInt(temp.toString());
					temp.setLength(0);
				}
			}
		}
		if(temp.length() > 0) {
			result += Integer.parseInt(temp.toString());
		}
		System.out.println(result);

}

- Anonymous April 14, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String s = "abc12fds3dsf7";
		int result = 0;
		StringBuilder temp = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if(Character.isDigit(c)) {
				temp.append(c);
			}
			else {
				if(temp.length() > 0) {
					result += Integer.parseInt(temp.toString());
					temp.setLength(0);
				}
			}
		}
		if(temp.length() > 0) {
			result += Integer.parseInt(temp.toString());
		}
		System.out.println(result);
	}

- Xiang April 14, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String s = "abc12fds3dsf7";
		int result = 0;
		StringBuilder temp = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if(Character.isDigit(c)) {
				temp.append(c);
			}
			else {
				if(temp.length() > 0) {
					result += Integer.parseInt(temp.toString());
					temp.setLength(0);
				}
			}
		}
		if(temp.length() > 0) {
			result += Integer.parseInt(temp.toString());
		}
		System.out.println(result);
	}

- Xiang April 14, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String s = "abc12fds3dsf7";
		int result = 0;
		StringBuilder temp = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if(Character.isDigit(c)) {
				temp.append(c);
			}
			else {
				if(temp.length() > 0) {
					result += Integer.parseInt(temp.toString());
					temp.setLength(0);
				}
			}
		}
		if(temp.length() > 0) {
			result += Integer.parseInt(temp.toString());
		}
		System.out.println(result);
	}

- xiang April 14, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String input1 = "adf12bgt3bh5j";
		String input2 = "iuy2hjg4jhg8";
		String input3 = "7 13";
		String token1=",";
		String token2=" ";

		System.out.println(separator(input1, token1));
		System.out.println(separator(input2, token1));
		System.out.println(separator(input3, token2));
	}

	public static Integer separator(String input, String token) {
		int strLen = input.length();

		ArrayList<Object> list = new ArrayList<Object>();
		int tmp = 0;

		for(int i=0; i<strLen; i++) {
			tmp = Character.getNumericValue(input.charAt(i));
			if(tmp< 10 && tmp > 0) {
				list.add(tmp);
			} else{
				if(tmp== -1) {
					list.add(" ");
				}
				list.add(token);
			}
		}

		String listString = token;
		for(Object s : list) {
			if(!s.equals(token)) {
				s = String.valueOf(s);
			}
			listString += s;
		}
		return tokener(listString, token);
	}

	public static Integer tokener(String str, String token) {
		StringTokenizer tokenizer = new StringTokenizer(str, token);

		int total=0;
		while(tokenizer.hasMoreTokens()){
			String tmp = tokenizer.nextToken();

			total = total + Integer.parseInt(tmp);
		}

		return total;
	}

- code.juno April 15, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Testing {
public static void main(String[] args)
{
String s1 = " 8 sometext 7 3";
String arr[] = s1.trim().split("[a-zA-Z ]+"); // Please note a space is there after Z

int sum = 0;

for (int i = 0; i < arr.length; i++)
sum += Integer.parseInt(arr[i]);

System.out.println(sum);
}
}

- Anonymous April 15, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String str = "  100a20b3c40d10";
		int sum=0;
		for(int i=0; i<str.length(); ){
			char x = str.charAt(i);
			String tmp=new String();
			int cnt=0;
			while(x>=48 && x <=57 ){
				tmp+=x;
				i++;
				if(i >= str.length()){
					break;
				}
				x = str.charAt(i);
				cnt++;
			}
			if(!tmp.isEmpty()){
				sum+= Integer.parseInt(tmp);
			}
			if(cnt <= 0){
				i++;
			}
		}
		System.out.println(sum);
	}

- Yogesh Bhardwaj April 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int AddDigitsInString(string input)
{
int i = 0, j = 0;
int value = 0;
int num;

char[] inArray = input.ToCharArray();
int[] sumArr = new int[inArray.Length];

for (i = 0; i <= inArray.Length - 1; i++)
{
if (char.IsDigit(inArray[i]))
{
num = int.Parse(Convert.ToString(inArray[i]));
value = value * 10;
value = value + num;

if(i == inArray.Length - 1)
{
sumArr[j] = value;
j++;
value = 0;
}
else if (!char.IsDigit(inArray[i + 1]) && i != inArray.Length - 1)
{
sumArr[j] = value;
j++;
value = 0;
}
}
}
for (i = 0; i <= sumArr.Length - 1; i++)
{
value = value + sumArr[i];
}
return value;
}

- Priyanka Patil April 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int AddDigitsInString(string input)
        {
            int i = 0, j = 0;
            int value = 0;
            int num;

            char[] inArray = input.ToCharArray();
            int[] sumArr = new int[inArray.Length];

            for (i = 0; i <= inArray.Length - 1; i++)
            {
                if (char.IsDigit(inArray[i]))
                {
                    num = int.Parse(Convert.ToString(inArray[i]));
                    value = value * 10;
                    value = value + num;

                    if(i == inArray.Length - 1)
                    {
                        sumArr[j] = value;
                        j++;
                        value = 0;
                    }
                    else if (!char.IsDigit(inArray[i + 1]) && i != inArray.Length - 1)
                    { 
                        sumArr[j] = value;
                        j++;
                        value = 0;
                    }
                }
            }
            for (i = 0; i <= sumArr.Length - 1; i++)
            {
                value = value + sumArr[i];
            }
            return value;
        }

- Priyanka Patil April 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int AddDigitsInString(string input)
{
int i = 0, j = 0;
int value = 0;
int num;

char[] inArray = input.ToCharArray();
int[] sumArr = new int[inArray.Length];

for (i = 0; i <= inArray.Length - 1; i++)
{
if (char.IsDigit(inArray[i]))
{
num = int.Parse(Convert.ToString(inArray[i]));
value = value * 10;
value = value + num;

if(i == inArray.Length - 1)
{
sumArr[j] = value;
j++;
value = 0;
}
else if (!char.IsDigit(inArray[i + 1]) && i != inArray.Length - 1)
{
sumArr[j] = value;
j++;
value = 0;
}
}
}
for (i = 0; i <= sumArr.Length - 1; i++)
{
value = value + sumArr[i];
}
return value;
}

- Priyanka Patil April 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int solution(String s){
String regex="\\d+";
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(s);
int sum=0;
while(m.find()){
String addend=m.group(0);
if(addend!=null){
sum=sum+Integer.parseInt(addend);
}
}
return sum;
}

- Dilesh April 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int solution(String s){
		String regex="\\d+";
		Pattern p=Pattern.compile(regex);
		Matcher m=p.matcher(s);
		int sum=0;
		while(m.find()){
			String addend=m.group(0);
			if(addend!=null){
				sum=sum+Integer.parseInt(addend);
			}
		}		
		return sum;
	}

- Dilesh April 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {String inp="asdf12rerf4asd5";
Pattern p=Pattern.compile("[0-9]+");
Matcher m=p.matcher(inp);
int i=0;
while (m.find()) { System.out.println(inp.substring(m.start(), m.end()));
i=i+Integer.parseInt(inp.substring(m.start(), m.end()));}
System.out.println(i) }

- Mohanraj April 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python :

def add_digits (inp_string):
    digit_list=[]
    j = -1
    i = 0
     
    while i < len(inp_string):
        if ( inp_string[i].isdigit()):
            j = j + 1
            digit_string = ""
            while (( i < len(inp_string)) and inp_string[i].isdigit()):
                digit_string  += inp_string[i]
                i = i + 1
            digit_list.insert(j,str(digit_string))
        i = i + 1
    sum = 0
    for each_digit in digit_list:
        sum += int(each_digit)
    return sum

- TinkerBell April 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def add_digits (inp_string):
    digit_list=[]
    j = -1
    i = 0
     
    while i < len(inp_string):
        if ( inp_string[i].isdigit()):
            j = j + 1
            digit_string = ""
            while (( i < len(inp_string)) and inp_string[i].isdigit()):
                digit_string  += inp_string[i]
                i = i + 1
            digit_list.insert(j,str(digit_string))
        i = i + 1
    sum = 0
    for each_digit in digit_list:
        sum += int(each_digit)
    return sum

- Tinkerbell April 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package corejava;
import java.util.*;
public class Str {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str=sc.next();
List l=new ArrayList();
char ch[]= new char[4];
ch=str.toCharArray();
System.out.println(ch);
try
{
for(int j=0;j<ch.length;j++)
{
int a= ch[j];
System.out.println(a);
for (int i=48;i<=57;i++)
{

if(a==i)
{
int l1=0;
l1=i-48;
l.add(l1);
}
}

}
}
catch(Exception e)
{
System.out.println("catch");
}
Iterator it = l.iterator();
int sum=0;
while(it.hasNext())
{

Object a=it.next();
int a1 =(Integer)a;
sum=sum+a1;
System.out.println(sum);

}
}
}

- Anonymous June 18, 2015 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More