Sum Of Embedded Numbers in a String

A Friend ask a question.
You have given a string which has embedded numbers, characters, special characters for example “ab-2cd34ef89x9a”. You need to find all the numbers from the string and return the sum of those numbers.

In this case number would be -2, 34, 89, 9 , and Sum would be 130

Here is my Java Solution for the same. If you find this is failing for any particular input let me know.

	public static void main(String[] args) {
		//String s1 = "ab-2cd34ef89x9a";
		//String s1 = "111111";
		//String s1 = "111a111";
		//String s1 = "ab-2cd34ef89x9a-";
		//String s1 = "ab-2cd34ef89x9a+";
		//String s1 = "ab-2c-d34ef89x9a+";
		int isNegative = 1;
		int sum = 0;
		java.util.Stack<Integer> numStack = new java.util.Stack<Integer>();
		for(char ch: s1.toCharArray()){
			if ( ch == '-') {
				isNegative = -1;
				continue; //fetch next character
			}
			if ( Character.isDigit(ch)) {
				numStack.push(Character.getNumericValue(ch));				
			} else {
				Iterator<Integer> iterator = numStack.iterator();
				int pow = numStack.size() - 1;
				int embeddedNumber = 0;
				
				while (iterator.hasNext()) {
					int i = (int) iterator.next();
					embeddedNumber += i * Math.pow(10, pow--);
				}
				sum += isNegative * embeddedNumber;
				numStack.clear();
				isNegative = 1;
			}
		}
		Iterator<Integer> iterator = numStack.iterator();
		int pow = numStack.size() - 1;
		int embeddedNumber = 0;
		
		while (iterator.hasNext()) {
			int i = (int) iterator.next();
			embeddedNumber += i * Math.pow(10, pow--);
		}
		sum += isNegative * embeddedNumber;
		
		System.out.println("SUM ==> " + sum);
		
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s