[알고리즘문제풀기] 더 크게 합치기

silver's avatar
Feb 14, 2025
[알고리즘문제풀기] 더 크게 합치기

문제

내가 작성한 정답

class Solution { public int solution(int a, int b) { String aa = Integer.toString(a); String bb = Integer.toString(b); String cc = aa+bb; String dd = bb+aa; int c = Integer.parseInt(cc); int d = Integer.parseInt(dd); return (c>=d)? c: d; } }
a ⊕ b와 b ⊕ a가 같다면 어떤 것을 리턴해도 값이 같기 때문에 Math.max를 사용해도 된다
class Solution { public int solution(int a, int b) { return Math.max(Integer.parseInt(Integer.toString(a)+Integer.toString(b)) , Integer.parseInt(Integer.toString(b)+Integer.toString(a))); } }
String + int ⇒ int가 자동으로 String으로 변환되어 글자가 합쳐지고 String으로 저장된다.
class Solution { public int solution(int a, int b) { return Math.max(Integer.parseInt(String.valueOf(a) + b), Integer.parseInt(String.valueOf(b) + a)); } }

다른 사람들의 정답

class Solution { public int solution(int a, int b) { int answer = 0; // 두 정수를 문자열로 변환하여 연결한 후 정수로 변환 // "" : 빈 문자열 -> String int aLong = Integer.parseInt("" + a + b); // a와 b를 연결한 정수 int bLong = Integer.parseInt("" + b + a); // b와 a를 연결한 정수 answer = aLong > bLong ? aLong : bLong; return answer; } }
💡
int -> String 변환 시
  1. 숫자+""
  1. String.valueOf() - null 처리 가능 “null”이라는 문자열로 반환
  1. Integer.toString() - null처리 불가능 : NullPointerException이 발생
  1. String.format() - 변수의 형식을 지정가능
    1. int number = 123; String str = String.format("%d", number); // "123"
  1. DecimalFormat
    1. import java.text.DecimalFormat; int number = 123; DecimalFormat df = new DecimalFormat("#"); String str = df.format(number); // "123"
 
Share article

silver