Light Blue Pointer
본문 바로가기
Coding Test

[프로그래머스][Lv.0]두 수의 연산값 비교하기

by Greedy 2023. 11. 3.

문제 주소

https://school.programmers.co.kr/learn/courses/30/lessons/181938

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 설명

연산 ⊕는 두 정수에 대한 연산으로 두 정수를 붙여서 쓴 값을 반환합니다. 예를 들면 다음과 같습니다.

  • 12 ⊕ 3 = 123
  • 3 ⊕ 12 = 312

양의 정수 a와 b가 주어졌을 때, a ⊕ b와 2 * a * b 중 더 큰 값을 return하는 solution 함수를 완성해 주세요.

단, a ⊕ b와 2 * a * b가 같으면 a ⊕ b를 return 합니다.


제한사항

  • 1 ≤ a, b < 10,000

입출력 예

a b result

2 91 364
91 2 912

입출력 예 설명

입출력 예 #1

  • a ⊕ b = 291 이고, 2 * a * b = 364 입니다. 둘 중 더 큰 값은 364 이므로 364를 return 합니다.

입출력 예 #2

  • a ⊕ b = 912 이고, 2 * a * b = 364 입니다. 둘 중 더 큰 값은 912 이므로 912를 return 합니다.

Python

제출 코드

def solution(a, b):
    concat = int(str(a)+str(b))
    if(concat>=2*a*b):
        return concat  
    return 2*a*b

다른사람의 풀이

def solution(a, b):
    return max(int(str(a) + str(b)), 2 * a * b)

⭐max() 쓰니까 편리하다

Python max() Function

Return the item with the highest value : max(n1, n2, n3, ...)

오 숫자가 아니어도 되나봄?

x = max(5, 10)//10
x = max("Mike", "John", "Vicky")//Vicky

Return the item with the highest value in an iterable: max(iterable)

a = (1, 5, 3, 9)
x = max(a)//9
def solution(a, b):
    res = int(str(a) + str(b))
    comp = 2*a*b
    return max(res,comp)

max 쓴 다른 사람

def solution(a, b):
    concat = int(str(a) + str(b))
    k = 2 * a * b
    return (concat if concat > k else k)

return 안에 if else 넣을 수 있는지 몰랐음

Java

풀이 과정

⭐Java String to integer

1.Using Integer.valueOf → Integer 객체로

Integer number;
String validString = "123";
number = Integer.valueOf(validString);

2.Using Integer.parseInt() → primitive type int로

int number;
String validString = "123";
number = Integer.parseInt(validString);

Integer.valueOf 와 Integer.parseInt() 를 쓸 때 생각해야 할 점

Note that both could throw a NumberFormatException

  • If you need to store the result in a database, then Integer is nullable which might be useful.
  • Integer includes other helper methods, which you might need if you do further processing after the conversion.
  • The primitive int can behave more predictably and manipulating int variables sometimes requires less code

제출 코드

class Solution {
    public int solution(int a, int b) {
        int concat = Integer.parseInt(""+a+b);
        if(concat>=2*a*b){
            return concat;
        }
        return 2*a*b;
    }
}

다른사람의 풀이

class Solution {
    public int solution(int a, int b) {
        return Math.max(Integer.parseInt(String.valueOf(a)+String.valueOf(b)),2*a*b);
    }
}

⭐Java에도 max()가 있네..?

Math.max()

  • static int max(int a , int b)
  • static double max(double a , double b)
  • static float max(float a , float b)
  • static long max(long a , long b)

Math.min()도 있음

⭐int를 String화 하는 새로운 방법

String.valueOf(a)