백준 2745번 진법 변환 (java)

마뇽미뇽·2024년 5월 8일
0

알고리즘 문제풀이

목록 보기
65/165

1.문제

https://www.acmicpc.net/problem/2745

2.풀이

https://velog.io/@gayeong39/%EB%B0%B1%EC%A4%80-2745-%EC%A7%84%EB%B2%95-%EB%B3%80%ED%99%98JAVA 님의 글을 참고하였다.

문장은 좌에서 우 방향으로 진행되는데, 진법은 우에서 좌 방향으로 읽어가야하기 때문에 반복문을 점점 줄어들도록한다.
진법을 변환할 때 16진법에선 문자를 사용할 때는 'A'를 8진법이나 2진법일때 아스키 코드에서 0을 뺀 수를 나오도록 한다.
A는 10이상일 때 사용하기 때문에 10을 더한다.

다른 풀이로는 Integer.parseInt() 로 풀어도 된다(나는 그냥 풀어보고 싶었다.)

3.코드

package com.example.baekjoon;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String s = sc.next();
        int n = sc.nextInt();

        int sum = 0;
        int pow = 1;

        for(int i = s.length() -1; i  >= 0; i--){
            char c = s.charAt(i);
            if(c >= 'A' && c <= 'z')
                sum += (c - 'A' + 10) * pow;
            else
                sum += (c - '0') * pow;

            pow *= n;
        }
        System.out.println(sum);
        sc.close();
    }
}
package com.example.baekjoon;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String n = sc.next();
        int b = sc.nextInt();

        final int res = Integer.parseInt(n,b);
        System.out.println(res);
    }
}
profile
Que sera, sera

0개의 댓글