This post is completed by 1 user
|
Add to List |
394. Find the maximum number present in a String
Given a string with alphabets and numbers. Write an algorithm to find the maximum number in the string. If any number is greater than equal to Max_Value of integer then return the Max_Value.
Example:
Input: "abcd 45, 54 and 50 are the numbers" Output: Maximum Number- 54 Input: aabb123ccdefgh54319hij Output: 54319 Input: 213123123and544455523412423423424234234234 Output: 2147483647 (Max value of Integer) Input: abcd Maximum Number- 0
Approach:
Recommended Article- String to Integer (AtoI - ASCII to Integer)
- Initialize max_so_far=0, current_no=0.
- Iterate the given string from left to right.
- If the character is number then start constructing current_no with all the contiguous characters with are number using ASCII to integer conversion. Once get the character which is not a number then update the max_so_far with current_no if max_so_far<current_no and make current_no =0.
- Keep track of current_no, once it reaches to Max_Value of Integer, return Max_Value.
- return max_so_far.
- See and run the code below for more understanding.
Output:
Input: abcd 45, 54 and 50 are the numbers Maximum Number- 54 Input: aabb123ccdefgh54319hij Maximum Number- 54319 Input: 213123123and544455523412423423424234234234 Maximum Number- 2147483647 Input: abcd Maximum Number- 0