-
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)); int N = Integer.parseInt(br.readLine()); int count=0; for(int i=1; i<= N;i++) { if(i<100) { count++; }else if(i<1000) { String input[] = Integer.toString(i).split(""); int first = Integer.parseInt(input[0]); int second = Integer.parseInt(input[1]); int third = Integer.parseInt(input[2]); if(second - first == third - second) { count++; } } } System.out.println(count); } }
규칙을 생각해보면,
i = 1 2 3 4 5 6 7 8 9 일때는 한수이다.
i = 10 ~ 99 까지도 두개의 수만 고려하기 때문에 한수이다.
예를 들어 17 이라면,
두 개의 수 1 과 7이 6만큼 차이나는 등차수열이다.
때문에 위의 코드에서도 i<100 인 경우 무조건 count 를 높여주었다.
그리고 남은 수는 100~1000 이다. (문제에서 1000보다 작거나 같은 자연수가 주어진다고 했다.)
1000은 등차수열이 아니기 때문에 고려할 대상이 아니라서 for 문에서 제외시켰다.
그런데 문제는 int 형은 각 자리수를 비교하려면 좀 복잡하다.
그래서 string 으로 받은 뒤, 다시 int 형으로 바꿔서 그 차이를 비교했다.
String input[] = Integer.toString(i).split("");
특히 이 코드는, int 형 i를 string 으로 변환하고 이를 공백을 기준으로 잘라서 배열로 만들어 넣어준다.
예를 들어 123 이라면,
first = Integer.parseInt(input[0]) = 1,
second = Integer.parseInt(input[1] = 2,
third = Integer.parseInt(input[2]) = 3
이다.
그래서 third - second = second - first 이면 등차수열이기 때문에
이 조건을 만족한다면 count 를 증가시켰다.
'백준 > 브루트 포스' 카테고리의 다른 글
14500 테트로미노 (0) 2022.04.24 2501 약수 구하기(자바) (0) 2022.02.19 1759 암호 만들기(자바) (0) 2022.02.03 2798 블랙잭 (0) 2021.10.18