The problem context involves validating IP addresses. An IP address is a string in the form of 'A.B.C.D', where the value of A, B, C, and D may range from 0 to 255. The task is to write a Java program that validates whether a given string is a valid IP address or not.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution approach involves using regular expressions. A static string 'zeroTo255' is defined to match any number from 0 to 255. This is then used to construct the pattern for a valid IP address. In the main method, the program reads a string and checks if it matches the defined pattern, thus validating if it is a valid IP address or not.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.strings;
import java.util.Scanner;
/**
*
*/
class MyRegex {
static String zeroTo255 = "(\\d{1,2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5])";
public static String pattern = zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255;
}
public class JavaRegex {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String IP = in.next();
System.out.println(IP.matches(new MyRegex().pattern));
}
in.close();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.