알고리즘/부르트포스

[백준] 1748 : 수 이어쓰기 1

믕비 2023. 4. 9. 21:50

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

 

1748번: 수 이어 쓰기 1

첫째 줄에 N(1 ≤ N ≤ 100,000,000)이 주어진다.

www.acmicpc.net

반복된 계산을 많이 해야 해서 아예 배열로 만들어서 계산함.

 

내 코드

메모리 : 14044 KB

시간 : 120 ms

코드길이 : 1693 B

 

[내 코드]

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

public class Main {
	static int[] num = {9, 90*2, 900*3, 9000*4, 90000*5, 900000*6, 9000000*7, 90000000*8};

	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		
		int N = Integer.parseInt(br.readLine());
		
		int result = 0;
		//일의자리
		if(1 <= N && N < 10) {
			result = N;
		}
		//십의자리
		else if(10 <= N && N < 100) {
			result = num[0] + (N - 10 + 1)*2;
		}
		//백의자리
		else if(100 <= N && N < 1000) {
			for(int i = 0 ; i < 2; i++) {
				result += num[i];
			}
			result += (N - 100 + 1)*3;
		}
		//천의자리
		else if(1000 <= N && N < 10000) {
			for(int i = 0 ; i < 3; i++) {
				result += num[i];
			}
			result += (N - 1000 + 1)*4;
		}
		//만의자리
		else if(10000 <= N && N < 100000) {
			for(int i = 0 ; i < 4; i++) {
				result += num[i];
			}
			result += (N - 10000 + 1)*5;
		}
		//십만의자리
		else if(100000 <= N && N < 1000000) {
			for(int i = 0 ; i < 5; i++) {
				result += num[i];
			}
			result += (N - 100000 + 1)*6;
		}
		//백만의자리
		else if(1000000 <= N && N < 10000000) {
			for(int i = 0 ; i < 6; i++) {
				result += num[i];
			}
			result += (N - 1000000 + 1)*7;
		}
		//천만의자리
		else if(10000000 <= N && N < 100000000) {
			for(int i = 0 ; i < 7; i++) {
				result += num[i];
			}
			result += (N - 10000000 + 1)*8;
		}
		//일억
		else if(100000000 == N) {
			for(int i = 0 ; i < 8; i++) {
				result += num[i];
			}
			result += 9;
		}
		sb.append(result);
		System.out.print(sb);
	}

}

 

1등 코드

메모리 : 11340 KB

시간 : 69 ms

코드길이 : 540 B

 

[1등 코드]

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

public class Main {
	static int N;

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(in.readLine());

		int ans = 0;
		for (int start = 1, len = 1; start <= N; start *= 10, len++) {
			int end = start * 10 - 1;
			if (end > N)
				end = N;
			ans += len * (end - start + 1);
		}
		System.out.println(ans);
	}

}

'알고리즘 > 부르트포스' 카테고리의 다른 글

[백준] 9095 : 1, 2, 3 더하기  (0) 2023.04.10
[백준] 6064 : 카잉 달력  (0) 2023.04.09
[백준] 1107 : 리모컨  (0) 2023.04.07
[백준] 1476 : 날짜계산  (0) 2023.04.07
[백준] 3085 : 사탕게임  (0) 2023.04.06