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

나의 답안 :
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;
}
}
}
불필요하게 일단 배열을 생성하는 버릇이 생긴 것은 아닌지... ?
변수만 사용했을 때 불필요한 반복문도 줄고, 시간과 메모리도 줄었다.

'오늘의 문제' 카테고리의 다른 글
| [백준 JAVA] 11720번 - 숫자의 합 (0) | 2022.06.02 |
|---|---|
| [백준 JAVA] 11654번 - 아스키 코드 (0) | 2022.06.02 |
| [백준 JAVA] 4344번 - 평균은 넘겠지 (0) | 2022.05.30 |
| [백준 JAVA] 8958번 - OX 퀴즈 (0) | 2022.05.28 |
| [백준 JAVA] 1546번 - 평균 (0) | 2022.05.27 |