728x90

https://school.programmers.co.kr/learn/courses/30/lessons/181939?language=java

 

프로그래머스

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

programmers.co.kr

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

-12 ⊕ 3 = 123
-3 ⊕ 12 = 312
양의 정수 a와 b가 주어졌을 때, a ⊕ b와 b ⊕ a 중 더 큰 값을 return 하는 solution 함수를 완성해 주세요.

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

 

 

 

 

 

풀이)

class Solution {
    public int solution(int a, int b) {
        int answer = 0;
        
        //정수형을 문자열으로 바꾸기
        String anw = Integer.toString(a)+Integer.toString(b);
        String anw1 = Integer.toString(b)+Integer.toString(a);
		
        //문자열을 정수형으로 바꾸기
        int a1 = Integer.parseInt(anw);
        int b1 = Integer.parseInt(anw1);

        answer = a1>=b1 ? a1 : b1;
        
        
        return answer;
    }
}

 


String을 int형으로 바꾸는 방법

문자열을 숫자로 바꾸는 방법은 크게 두 가지 가 있다.

바로 java.lang.Integer클래스의 valueOf()메소드와 parseInt()메소드이다.

1. Integer.parseInt() 메서드 사용

String stringValue = "42";
int intValue = Integer.parseInt(stringValue);

이 방법은 문자열을 정수로 변환합니다. 그러나 변환하려는 문자열이 정수가 아닌 경우 NumberFormatException이 발생할 수 있다.

따라서 이 메서드를 사용할 때는 예외 처리를 고려해야 함!!

try {
    String stringValue = "42";
    int intValue = Integer.parseInt(stringValue);
    // 변환 성공 시 처리
} catch (NumberFormatException e) {
    // 변환 실패 시 처리
    e.printStackTrace();
}

2. Integer.valueOf() 메서드 사용

String stringValue = "42";
int intValue = Integer.valueOf(stringValue);

parseInt()과 비슷하게 동작하지만, 반환값이 int가 아닌 Integer 객체이다.

 


 int형을 String 으로 바꾸는 방법

숫자형을 문자열로 바꾸는 방법은 크게 4가지가 있다.

1. String.valueOf() 메서드 사용

int intValue = 42;
String stringValue = String.valueOf(intValue);

2. Integer.toString() 메서드 사용

int intValue = 42;
String stringValue = Integer.toString(intValue);

3. "" 연산자를 이용한 간단한 방법

int intValue = 42;
String stringValue = "" + intValue;

4. String.format() 메서드 사용

int intValue = 42;
String stringValue = String.format("%d", intValue);
728x90