๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ”Ž Algorithm/๐Ÿ’ป ๋ฌธ์ œ ํ’€์ด

[๋ฐฑ์ค€] 1436. ์˜ํ™”๊ฐ๋… ์Š˜

by Seongpyo Hong 2021. 2. 3.

๋ฌธ์ œ

ํ’€์ด

์ฐพ์€ ๊ทœ์น™์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

  • prefix๋ฅผ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ์œ ์ง€ํ•˜๊ณ  1์‚ฌ์ดํด์ด ๋๋‚˜๋ฉด prefix๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
  • ์ฒ˜์Œ 0~5๊นŒ์ง€๋Š” prefix์™€ 666์‚ฌ์ด์— ๋ถ™ํžŒ๋‹ค. ex) 1666, 2666, 11666
  • prefix 6์ด ๋‚˜์˜ค๋ฉด ๋’ค์—์„œ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์กฐํ•ฉ์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋Š˜์–ด๋‚จ 
    ex) prefix 1 => ๋’ค์— 10๊ฐœ / prefix 16 ⇒ ๋’ค์— 100๊ฐœ / prefix 166 ⇒ ๋’ค์— ์กฐํ•ฉ 1000๊ฐœ
  • ๊ฒฐ๋ก ์€ 1์‚ฌ์ดํด์€ 6 + (10^prefix์˜ 6์˜ ๊ฐœ์ˆ˜) + 3 ์˜ ๊ทœ์น™์„ ๊ฐ€์ง€๊ฒŒ ๋œ๋‹ค.

๋‹ค ํ‘ผ๋’ค์— ์ƒ๊ฐํ•ด๋ณด๋‹ˆ Input์ด ์ž‘์•„์„œ 1๋ถ€ํ„ฐ ๋ชจ๋“  ์ˆ˜๋ฅผ ๋Œ๋ฉฐ 666์ด ํฌํ•จ๋  ๊ฒฝ์šฐ ์นด์šดํŠธ ํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™๋‹ค.

import java.util.Scanner;

public class Solution {
	private static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		int N = sc.nextInt() - 1;

		if (N == 0) {
			System.out.println("666");
			return;
		}

		int prefix = 0;
		int cnt;
		while (true) {
			cnt = 1;
			if (prefix % 10 == 6)
				cnt++;
			if (prefix % 100 == 66)
				cnt++;

			int limit = (int) Math.pow(10, cnt) + 9;
			if (N / limit == 0)
				break;

			N -= limit;
			prefix++;
		}

		String body = "";
		for (int i = 3; i >= cnt; i--) {
			body += "6";
		}
		
		StringBuilder sb = new StringBuilder();

		if (prefix != 0) {
			sb.append(String.valueOf(prefix));
		}

		if (N < 6) {
			sb.append(N + "666");
		} else {
			int limit = (int) Math.pow(10, cnt) + 6;
			if (N < limit) {
				sb.append(body + getFormatNum(cnt, N - 6));
			} else {
				sb.append((N - (int) Math.pow(10, cnt) + 1) + "666");
			}
		}
		
		System.out.println(sb.toString());
		
	}
	
	private static String getFormatNum(int len, int target) {
		StringBuilder sb = new StringBuilder();
		sb.append(String.valueOf(target));
		for (int i = sb.length(); i < len; i++) {
			sb.insert(0, '0');
		}
		return sb.toString();
	}

}

๋Œ“๊ธ€