Please solve in c++
Split the Number
Programming challenge description:
You are given a number N and a pattern. The pattern consists of
lowercase latin letters and one operation "+" or "-". The challenge
is to split the number and evaluate it according to this pattern
e.g.
1232 ab+cd -> a:1, b:2, c:3, d:2 -> 12+32 -> 44
Input:
Your program should read lines from standard input. Each line contains the number and the pattern separated by a single whitespace. The number will be in range [100, 1000000000]. All test cases contain valid expressions (no leading zeros).
Output:
Print out the result of the pattern evaluation.
Test 1
Test InputDownload Test 1 Input
3413289830 a-bcdefghij
Expected OutputDownload Test 1 Input
-413289827
Test 2
Test InputDownload Test 2 Input
776 a+bc
Expected OutputDownload Test 2 Input
83
import java.io.BufferedReader; |
import java.io.File; |
import java.io.FileReader; |
import java.io.IOException; |
public class SplittheNumber { |
@SuppressWarnings("resource") |
public static void main(String[] args) throws IOException { |
File file = new File("files/easy/test_SplittheNumber.txt"); |
BufferedReader buffer = new BufferedReader(new FileReader(file)); |
String line; |
while ((line = buffer.readLine()) != null) { |
line = line.trim(); |
String[] words = line.split(" "); |
long result = 0; |
if (words[1].contains("+")) { |
String[] splitted = words[1].split("\\+"); |
result = Long.parseLong(words[0].substring(0, splitted[0].length())) |
+ Long.parseLong(words[0].substring(splitted[0].length())); |
} else if (words[1].contains("-")) { |
String[] splitted = words[1].split("-"); |
result = Long.parseLong(words[0].substring(0, splitted[0].length())) |
- Long.parseLong(words[0].substring(splitted[0].length())); |
} |
System.out.println(result); |
} |
} |
}
Get Answers For Free
Most questions answered within 1 hours.