PROBLEM LINK:
Author: Gedi Zheng
Tester: Shiplu Hawlader
Editorialist: Praveen Dhinwa
DIFFICULTY:
Simple
PREREQUISITES:
processing of strings and arrays.
PROBLEM:
Given a string s, You have to replace some characters of it by a predefined mapping. After application of the mapping, it is guaranteed that you can
read the string as a real number in base 10 notation. For a given number, you need to find its shortest notation. Please Have a look at explanation
section to understand the definition of shortest notation.
EXPLANATION
Lets take some cases to understand what shortest notation of a real number means.
- For 5.50, Last 0 is irrelevant. Shortest representation of it will be 5.5.
- Similarly for 5.00, it will be 5.
- For 00.5 it will be .5
- For 00.00500 it will be .005
- For 0000 it will be 0
- For 500 it will be 500
- For 00500 it will be 500
Now let us divide the situation into two cases.
-
If the number contains decimal mark.
-
Remove the starting few zero digits until we get a non zero digit (ie starting irrelevant digits).
eg.
In the case of 05, we need to remove starting 0 only. Its shortest representation will be 5
In the case of 0.5, we need to remove starting 0 only. Its shortest representation will be .5 -
Find the point of occurrence of decimal mark, Remove the last irrelevant digits (zero digits) occurring after the decimal.
eg.
- If we are left with cases like 5.5550, then we need to remove the last zeros, So shortest representation will be 5.555 -
When the decimal is itself irrelevant, then we will remove the decimal too. You can see that decimal will be irrelevant if your number
doesn’t contain any relevant digit after the decimal point.
eg.
- In case of 5.00, We will remove both the zeros and decimal. Its shortest representation will be 5
- In case of 5., We will remove the decimal. Its shortest representation will be 5
-
-
If the number does not contain decimal mark.
- Remove the starting irrelevant digits.
eg 0055500 will become 555000. - Note that lase zeros in this case are always relevant, You can not convert 550 to 55.
- Special case: You need to take care of the case when the number is all 0’s. Answer in that case will be a single 0.
- Remove the starting irrelevant digits.
Few Tricky Test Cases
- Shortest representation for 0.00, .00, 0., 000, ., will be just a single 0
- Shortest representation for 0, 00, 0(repeated x times) will be just a single 0
- Shortest representation for 500.0, 500 will be 500
- Shortest representation for 0.5, 00.50 will be .5
Complexity:
O(N), You just need to check above given conditions. You just need constant amount of passes over the string s.