Coder Social home page Coder Social logo

codingtest's Introduction

header

🌱 Tech Stack



🏅 GitHub Stats

Anurag's GitHub stats

codingtest's People

Contributors

jangyoujung avatar

Stargazers

 avatar

Watchers

 avatar

codingtest's Issues

[JAVA] String to Integer 쉽고 간단하게 해결하는 방법 / 2023 KAKAO Blind Recruitment 개인정보 수집 유효 기한 문제 수정본

1. 파싱 사용 전 🔒

이는 바로 직전에 올린 카카오의 '개인 정보 수집 유효 기간'의 정석 풀이법을 찾아보면서 알아낸 유용한 메서드이다.
내가 해당 문제에서 문자열 -> 정수로 변환할 때 사용했던 코드를 보자.

int t_year = (today.charAt(0)-'0')*1000 + (today.charAt(1)-'0')*100 + (today.charAt(2)-'0')*10 + (today.charAt(3)-'0');
int t_month = (today.charAt(5)-'0')*10 + (today.charAt(6)-'0');
int t_day = (today.charAt(8)-'0')*10 + (today.charAt(9)-'0');

Parse라는 문자열을 정수로 쉽게 변환해 주는 메서드가 있는지 몰랐던 나는 하나하나 charAt을 사용해 열심히 고생할 수밖에 없었다.
그럼 이제 String을 Integer로 ParseInt를 사용해서 쉽게 바꿔보자!

int t_year = Integer.ParseInt(today.substring(0,4));
int t_month = Integer.ParseInt(today.substring(5,7));
int t_day = Integer.parseInt(today.substring(8,10));

이렇게 ParseInt와 Substring 메서드를 사용하면 쉽게 문자열을 정수로 변환할 수 있다.

이 두 메서드를 사용해서 수정한 코드는 아래와 같다.

2. 파싱 사용 후 🗝️

import java.util.Vector;
class Solution {
    public static int[] solution(String today, String[] terms, String[] privacies) {
        Vector<Integer> vector = new Vector<Integer>();

        //[0] today 년, 월, 일 분리하기
        int t_year = Integer.parseInt(today.substring(0,4));
        int t_month = Integer.parseInt(today.substring(5,7));
        int t_day = Integer.parseInt(today.substring(8,10));


        for(int index = 0; index<privacies.length; index++){
            String p = privacies[index];

            int left_months = 0; //유효 기간

            // [1] terms에서 개인정보 약관 종류 찾아서 유효기간 가져오기
            for(String t : terms ) {
                double digit = 0;
                if (t.charAt(0) == p.charAt(p.length() - 1)) {
                    for (int i = t.length()-1; ; i--) {
                        if(t.charAt(i)==' ')break;
                        else{
                            double num = (t.charAt(i) - '0') * Math.pow(10, digit);
                            left_months += (int) num;
                            digit++;
                        }
                    }
                    break;
                }
            }

            //[2]: privacies 년 / 월 / 일 각각 분리하기
            int p_year = Integer.parseInt(p.substring(0,4));
            int p_month =  Integer.parseInt(p.substring(5,7));
            int p_day = Integer.parseInt(p.substring(8,10));

            //[3]: left_months를 가지고 deadline 계산하기
            p_year+=left_months/12;
            p_month+=left_months%12;

            if(p_month>12) {
                p_year+=p_month/12;
                p_month%=12;
            }


            //[4]: 오늘 날짜와 비교해서 유효기간 지났는지 확인
            // [4]-1 연도가 이미 지났을 경우
            if(t_year>p_year){
                vector.add(index+1);
            }
            else if(t_year==p_year){
                //[4]-2 같은 연도에서 유효기간 달이 지났을 경우
                if(t_month>p_month) {
                    vector.add(index+1);
                }
                //[4]-3 같은 연도, 같은 달에서 하루 이상 지났을 경우
                else if(t_month==p_month && t_day>=p_day){
                    vector.add(index+1);
                }
            }
        }

        int[] answer = new int[vector.size()];
        for(int i =0; i<vector.size(); i++){
            answer[i]=vector.elementAt(i);
        }
        return answer;
    }
}

[JAVA] 2023 KAKAO Blind Recruitment 개인정보 수집 유효 기한 문제 풀이 / 프로그래머스 17번 반례

🔒 문제 설명:
https://school.programmers.co.kr/learn/courses/30/lessons/150370?language=java#
고객의 약관 동의를 얻어서 수집된 1~n번으로 분류되는 개인정보 n개가 있습니다. 약관 종류는 여러 가지 있으며 각 약관마다 개인정보 보관 유효기간이 정해져 있습니다. 당신은 각 개인정보가 어떤 약관으로 수집됐는지 알고 있습니다. 수집된 개인정보는 유효기간 전까지만 보관 가능하며, 유효기간이 지났다면 반드시 파기해야 합니다.

예를 들어, A라는 약관의 유효기간이 12 달이고, 2021년 1월 5일에 수집된 개인정보가 A약관으로 수집되었다면 해당 개인정보는 2022년 1월 4일까지 보관 가능하며 2022년 1월 5일부터 파기해야 할 개인정보입니다.
당신은 오늘 날짜로 파기해야 할 개인정보 번호들을 구하려 합니다.

🗝️ 문제 풀이:

import java.util.Vector;

class Solution {
    public static int[] solution(String today, String[] terms, String[] privacies) {

        Vector<Integer> vector = new Vector<Integer>();

        //[0] today 년, 월, 일 분리하기
        int t_year = (today.charAt(0)-'0')*1000 + (today.charAt(1)-'0')*100 + (today.charAt(2)-'0')*10 + (today.charAt(3)-'0');
        int t_month = (today.charAt(5)-'0')*10 + (today.charAt(6)-'0');
        int t_day = (today.charAt(8)-'0')*10 + (today.charAt(9)-'0');


        for(int index = 0; index<privacies.length; index++){
            String p = privacies[index];

            int left_months = 0; //유효 기간

            // [1] terms에서 개인정보 약관 종류 찾아서 유효기간 가져오기
            for(String t : terms ) {
                double digit = 0;
                if (t.charAt(0) == p.charAt(p.length() - 1)) {
                    for (int i = t.length()-1; ; i--) {
                        if(t.charAt(i)==' ')break;
                        else{
                            double num = (t.charAt(i) - '0') * Math.pow(10, digit);
                            left_months += (int) num;
                            digit++;
                        }
                    }
                    break;
                }
            }

            //[2]: privacies 년 / 월 / 일 각각 분리하기
            int p_year = (p.charAt(0)-'0')*1000 + (p.charAt(1)-'0')*100 + (p.charAt(2)-'0')*10 + (p.charAt(3)-'0');
            int p_month =  (p.charAt(5)-'0')*10 + (p.charAt(6)-'0');
            int p_day = (p.charAt(8)-'0')*10 + (p.charAt(9)-'0');

            //[3]: left_months를 가지고 deadline 계산하기
            p_year+=left_months/12;
            p_month+=left_months%12;

            if(p_month>12) {
                p_year+=p_month/12;
                p_month%=12;
            }

            System.out.println("deadline: "+p_year+"년 "+p_month+"월 "+p_day);///////

            //[4]: 오늘 날짜와 비교해서 유효기간 지났는지 확인
            // [4]-1 연도가 이미 지났을 경우
            if(t_year>p_year){
                vector.add(index+1);
            }
            else if(t_year==p_year){
                //[4]-2 같은 연도에서 유효기간 달이 지났을 경우
                if(t_month>p_month) {
                    vector.add(index+1);
                }
                //[4]-3 같은 연도, 같은 달에서 하루 이상 지났을 경우
                else if(t_month==p_month && t_day>=p_day){
                    vector.add(index+1);
                }
            }
        }

        int[] answer = new int[vector.size()];
        for(int i =0; i<vector.size(); i++){
            answer[i]=vector.elementAt(i);
        }
        return answer;
    }
}

📘 어려웠던 부분
[3]번에 left_month를 가지고 deadline을 계산하는 부분 코드를 구성하면서 정말 단순함에도 많이 헤맸는데
내 초기 코드는 아래와 같았다.

//[3]: left_months를 p_month에 더하고 시작하기 (오류)
	p_month+=left_month;

	if(p_month>12){
		p_year+=p_month/12;
		p_month%=12;
		if(p_month==0) p_month=12;
	}

먼저 남은 달을 p_month에 더하고, 그게 12를 넘어가면 p_year에 누적해가는 형태였다.
하지만 이것은 좋지 못한 풀이였다. 17번의 반례이기도 하다.

🔥 프로그래머스 17번 반례:
입력값 〉 "2020.12.17", ["A 12"], [ "2019.12.17 A"]
기댓값 〉 [1]
결과값 〉 [ ]

위 반례에서 p_month에 left_month를 더하면 p_month는 24가 된다. 그걸 12로 나눈 값을 연도에 더하면 2를 더하게 되어 deadline이 2021년 12월 17일이 되는 것이다. (정답은 2020년 12월 17일)

그러므로 left_month를 먼저 분해하고 그 값을 p_month에 더하는 방향으로 코드를 수정했다.

 //[3]: left_months를 먼저 분해하고, 값을 누적하기
            p_year+=left_months/12;
            p_month+=left_months%12;

            if(p_month>12) {
                p_year+=p_month/12;
                p_month%=12;
            }

결과는 성공적!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.