프로그래머스/자바(JAVA)

[자바(JAVA)] 양꼬치, 피자 나눠먹기, 옷가게 할인 받기,점의 위치 구하기,아이스 아메리카노, 제곱수 판별하기(Math.sqrt)

xlxlxl7 2023. 5. 25. 02:11
728x90

1. 양꼬치

// 내 풀이

class Solution {
    public int solution(int n, int k) {
        int price1 = 12000 * n;              // 양꼬치 총 몇 인분인지
        int freeCount = (n / 10);            // 양꼬치 10인분당 음료서비스 1개 산출
        int price2 = 2000 * (k - freeCount); // 총 음료에서 서비스 제외
                
        int answer = price1 + price2;
        return answer;
    }
}

 

 

// 다른사람 풀이
class Solution {
    public int solution(int n, int k) {
        int answer = 0;

        answer= n*12000 + (k-n/10)*2000;

        return answer;
    }
}
[본인 풀이의 코드가 길어진 이유]

1) 매개변수 선언시 데이터 타입(int)을 이미 설정했기 때문에 int price1,2를 선언할 필요가 없음
2) 단순연산만 필요하기 때문에 굳이 연산식을 따로 정의할 필요가 없음

 

 

2. 피자 나눠먹기 (1)

 

class Solution {
    public int solution(int n) {
        return (n % 7 == 0)? n / 7 : n / 7 + 1;
    }
}

 

 

3. 피자 나눠먹기 2

class Solution {
    public int solution(int slice, int n) {
        return (n % slice == 0)? n/slice : n/slice + 1 ;
    }
}

 

 

4. 점의 위치 구하기

class Solution {
    public int solution(int[] dot) {
        int x = dot[0];
        int y = dot[1];
        int answer = 0;
        
        if (x > 0 && y > 0) answer = 1;
        else if (x < 0 && y > 0) answer = 2;
        else if (x < 0 && y < 0) answer = 3;
        else if (x > 0 && y < 0) answer = 4;
        
        return answer;
    }
}

 

 

5. 아이스 아메리카노

class Solution {
    public int[] solution(int money) {
        
        int[] answer = new int[2];
        
        answer[0] = money / 5500;  // 몫 = n잔
        answer[1] = money % 5500;  // 나머지 = 잔돈
   
        return answer;
    }
}

 

 

6. 옷가게 할인 받기

class Solution {
    public int solution(int price) {
       int answer = 0;

        if (price >= 500000) {
            answer = (int) (price * 0.8);
        } else if (price >= 300000) {
            answer = (int)(price * 0.9);
        } else if (price >= 100000) {
            answer = (int)(price * 0.95);
        }
        return answer;
    }
}

 

 

7. 제곱수 판별하기

 

class Solution {
    public int solution(int n) {
        return Math.sqrt(n) % 1 == 0 ? 1 : 2;
    }
}

 

📌Math.sqrt() : 숫자의 제곱근을 반환하는 함수 

 

ex) 14의 제곱근 

출력값

n이 어떤수의 제곱이라면 출력값이 정수로 나옴

즉, 출력값 % 1 = 0이므로 아래와 같이 사용할 수 있다.

return Math.sqrt(n) % 1 == 0 ? 1 : 2;

 

728x90