Implement the validateIpSegmentSimple method that checks whether a text segment is valid for an IP address part.

The input contains a string segment. Your task is to check whether it is a valid IPv4 address segment.

A valid segment must contain only digits, must represent a number from 0 to 255, and must not have leading zeros unless the segment is exactly 0. For example, 255 is valid, 256 is invalid, and 01 is invalid.

Example 1

Input
segment (string) = 255
Returns (boolean) true

Example 2

Input
segment (string) = 256
Returns (boolean) false

Example 3

Input
segment (string) = 1
Returns (boolean) false

Validate the segment using the standard IPv4 rules.

First reject empty strings and strings containing non-digit characters. Then reject segments with more than one character that start with 0, because leading zeros are not allowed.

Finally, convert the segment to a number and check whether it is between 0 and 255.

Pseudocode:

function validateIpSegmentSimple(segment):
    if segment is empty:
        return false
    if segment contains any non-digit character:
        return false
    if length(segment) > 1 and segment[0] == '0':
        return false
    value = convert segment to integer
    return value >= 0 and value <= 255
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.