Python | C++ | Remove leading zeros from an IP address
Given an IP address, remove leading zeros from the IP address.
Input : 100.020.003.400 Output : 184.108.40.2060 Input :001.200.001.004 Output : 220.127.116.11
The approach is to split the given string by “.” and then convert it to an integer which removes the leading zeros and then join back them to a string.To convert a string to an integer we can use int(s) and then convert it back to string by str(s) and then join them back by using join function.
Method 2 : Regex
Using a capture group, match the last digit and copy it and prevents all the digits from being replaced.
regex \d can be explained as:
- \d : Matches any decimal digit
\d Matches any decimal digit, this is equivalent to the set class [0-9].
- \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b
regex \b can be explained as:
\b allows you to perform a "whole words only" search u sing a regular expression in the form of \bword\b
Method 3: Storing the index of the first non zero character.
The approach is to split the string by “.” and store it in another string x.
Now get the index of the first non-zero character of that string and store
it in another variable ind. Initialise that variable to -1 which indicates that there is
no non-zero character in the string .In another variable append the substring picking
up characters from that index till the end in another string y.
Source code : c++ solution