[codesignal] isIPv4 address

반응형
반응형

An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.

Given a string, find out if it satisfies the IPv4 address naming rules.

Example

  • For inputString = "172.16.254.1", the output should be
    isIPv4Address(inputString) = true;

  • For inputString = "172.316.254.1", the output should be
    isIPv4Address(inputString) = false.

    316 is not in range [0, 255].

  • For inputString = ".254.255.0", the output should be
    isIPv4Address(inputString) = false.

    There is no first number.

Input/Output

  • [execution time limit] 3 seconds (java)

  • [input] string inputString

    A string consisting of digits, full stops and lowercase English letters.

    Guaranteed constraints:
    1 ≤ inputString.length ≤ 30.

  • [output] boolean

    • true if inputString satisfies the IPv4 address naming rules, false otherwise.

 

이 문제는 주어진 주소?가 ipv4주소인지 확인하는 비교적 간단한 문제다.

여기서 ipv4 는 최소 0.0.0.0 ~ 255.255.255.255 까지를 말한다.

더 디테일하게 말하는건 이 문제에서는 의미 없을것 같다.

숫자만 나오면 문제가 조금더 쉬워질지도 모르지만 이 문제는

문자도 등장하게 된다. 또 00같은 문자열도 등장한다. 이를 막아야한다.ㅜㅜ

boolean isIPv4Address(String inputString) {
    int increase = 0;
    String temp = "";
    List<String> ip4 = new ArrayList<>();
    List<Integer> iip4 = new ArrayList<>();
    for(int i = 0; i<inputString.length();i++) {
        if (inputString.charAt(i) == '.') {
        increase++; 
        ip4.add(temp);
        temp = "";       
        }else
          temp += inputString.charAt(i);  
          
          if (i == inputString.length()-1) {
              ip4.add(temp);
          }
    }
    
    for(String ip : ip4) {
        if (ip == null || ip.equals("")) {
            return false;
        }
        
        if (ip.length() >= 2 && ip.charAt(0) == '0') return false; 
        
        for(char c : ip.toCharArray()) {
            int t = c - '0';
            if (t <  0 || 9 < t) {
                return false;
            }
       }
       if (ip.length() > 3) return false;
       
       iip4.add(Integer.valueOf(ip));
    }
    
    for(int ip : iip4) {
        if ( ip < 0  || 255 < ip ) return false;
    }
    
    if (increase != 3) return false;
    return true;
}

 

처음에 "."을 기준으로 split하려 했지만 예상외로 잘 되지 않아 다른 방법을 선택하였다.

가장 맨위의 for문은 값을 추가하는데 int값으로 추가하는 것이 아니라

String값으로 추가하였다. 왜냐하면 int로 추가하게 되면

123같은 경우 6이라는 숫자가 저장 되기 때문이다. 이를 방지하고자

문자열로 저장하였다.

모든 문자열을 저장하지 않고 .이 나올때마다 저장해야될 문자열을 초기화했다.

즉 124.125 라면 124가 저장이 되고 . 등장했을때 다시 125가 저장된다는 뜻이다.

그런데 이렇게 하다보면 맨 마지막을 저장하지 않는다. 여기에는 몇 가지 방법이 있다.

첫번째 방법은 if문을 사용해서 마지막때 한번더 저장 시키는 방법이 있겠고

두번째 방법은 기존 문자열에서 마지막에 .을추가한 값을 가지고 for문을 돌리는 방법이 있다.

 

이렇게 준비한 list를 가지고

총 3가지의 예외를 처리할 수 있다.

첫번째는 빈 문자열일 경우다 예를들어 .12.5같은 문자열이 있다고 가정한다면 맨 앞자리는 아무것도 들어가지 않는 상태에서 리턴이 된다. 만약 이에 해당 된다면 false를 리턴하도록 했다.

두번째는 00같은 숫자다

왜 이것을 예외처리하는 이유는 int값으로 넘어가게 되면 00이아니라 0으로 합쳐지가 때문이다.,

즉 0+0은 0이라는 소리다.

이것은 간단히 자릿수가 2자리이상인데 앞자리가 0인 경우는 모조리 false로 리턴 시켜줬다.

마지막 세번째는 char값을 int로 바꾸는 과정에서 발생되는데 여기서 숫자가 아닌 값이 들어있을 경우 false를 return시켜준다.

이렇게 다시 Integer list에 저장시켜줬다.

마지막은 0부터 255를 벗어나는 값이라면 false를 리턴시켜줬다.

그런데 int값보다 크고 long보다 큰값이 들어올 수 있다.  그럴때는 자리수가 3을 넘어가면 false로 리턴 시켜줬다.

그리고 이 모든 것에 해당 되지 않는다면 true를 리턴시켜줬다.

 

 

? 한줄로도 끝나는 구나... 

반응형

'알고리즘' 카테고리의 다른 글

[codeSignal] rotateImage  (0) 2020.07.22
[codeSignal] avoidObstacles  (0) 2020.07.18
[codesignal] commonCharacterCount  (0) 2020.07.13
집합 알고리즘 구현  (0) 2020.07.07
[알고스팟] 문제 아이디 : RATIO 승률 올리기  (0) 2020.06.18

댓글

Designed by JB FACTORY