Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Life Engineering

[SWEA 5604] 구간 합 (Java) 본문

Problem Solving

[SWEA 5604] 구간 합 (Java)

흑개 2022. 4. 13. 00:12

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWXGGNB6cnEDFAUo 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Solution_SWEA_5604 {
	static int T;
	static long A, B;
	static long[] numbers;
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=null;
		T=Integer.parseInt(br.readLine());
		for (int t=1; t<=T; t++) {
			st=new StringTokenizer(br.readLine());
			A=Long.parseLong(st.nextToken());
			B=Long.parseLong(st.nextToken());
			long mul=1;
			numbers=new long[10];
			while (A<=B) {
				while (B%10!=9 && A<=B) {
					calc(B, mul);
					B--;
				}
				if (A>B) break;
				while (A%10!=0 && A<=B) {
					calc(A, mul);
					A++;
				}
				A/=10;
				B/=10;
				for (int i=0; i<10; i++) {
					numbers[i]+=((B-A+1)*mul);
				}
				mul*=10;
			}
			long answer=0;
			for (int i=0; i<10; i++) {
				answer+=(i*numbers[i]);
			}
			System.out.println("#"+t+" "+answer);
		}

	}
	private static void calc(long n, long mul) {
		long temp=n;
		while (temp>0) {
			numbers[(int)(temp%10L)]+=(mul);
			temp/=10;
		}
	}

}

어려워서 힌트보고 풀었다..

개인적으로 https://www.slideshare.net/Baekjoon/baekjoon-online-judge-1019 (백준 1019번 풀이) 가 도움이 많이 되었다

 

이 문제의 포인트는 두개의 숫자 끝자리가 각각 0, 9일때 어떤지를 관찰해서, 이 법칙을 이용해

A, B 끝자리를 0, 9로 만들어 준 후 나타난 숫자의 횟수를 저장해 준다는 점이다.

그리고 자릿수별로 나타난 숫자의 횟수를 계산해주는 점을 잊지 말자.