Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
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 31
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

[백준 JAVA] 1065번 - 한수 본문

오늘의 문제

[백준 JAVA] 1065번 - 한수

jeongwon_ 2022. 6. 1. 19:29

 

나의 답안 : 

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


public class Main{

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println(arithmeticProgression(Integer.parseInt(br.readLine())));
		br.close();
	}		

	public static int arithmeticProgression(int n) {
		int[] arr = new int[3];	//1000은 제외할 것이므로 3개짜리 배열 생성
		int count=0;

		if(n<100) return n;

		if(n>=100) {
			if(n==1000) n--;					
			while(n>=100) {	
				int a=n;
				while(a!=0) {
					for(int j=2; j>=0; j--) {	//배열 각 자리에 담기
						arr[j] = a%10;
						a=a/10;						
					}					
				}	
				if(arr[0]-arr[1]==arr[1]-arr[2])
					count++;					
				n--;
			}
		}
		return count+99;
	}
}

 

추가 답안: (배열 없이 변수로만)

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


public class Main{

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println(arithmeticProgression(Integer.parseInt(br.readLine())));
		br.close();

	}		

	public static int arithmeticProgression(int n) {

		int count=0;

		if(n<100) return n;

		else {
			while(n>=100) {
				int a = n/100;
				int b = (n/10)%10;
				int c = n%10;
				if(a-b==b-c)
					count++;
				n--;
			}
			return count+99;		

		}
	}
}

 

불필요하게 일단 배열을 생성하는 버릇이 생긴 것은 아닌지... ?

변수만 사용했을 때 불필요한 반복문도 줄고, 시간과 메모리도 줄었다.