[Java]한수

박상준·2023년 8월 15일
0

코딩테스트

목록 보기
12/19
package org.example.한수;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) {
        FastReader fr = new FastReader();
        int n = fr.nextInt();
        solution(n); // 99
    }
    
    private static void solution(int n) {
        int hanCount = 0;
        for (int x = 1; x <= n; x++) {
            Number xNumber = new Number(x);
            if (xNumber.isHanNumber()) {
                hanCount++;
            }
        }
        System.out.println(hanCount);
    }
    
    public static class Number {
        private final int value;
        
        public Number(int value) {
            if (!(1 <= value && value <= 1000)) {
                String errorMessage = MessageFormat.format("x => {0}, x 는1000보다 작거나 같은 자연수여야합니다.", value);
                throw new IllegalArgumentException(errorMessage);
            }
            this.value = value;
        }
        
        public boolean isHanNumber() {
            if (this.value < 100) {
                return true;
            }
            int temp = this.value;
            int firstDigit = temp % 10;
            temp /= 10;
            int secondDigit = temp % 10;
            int diff = firstDigit - secondDigit;
            
            while (temp >= 10) {
                firstDigit = temp % 10;
                temp /= 10;
                secondDigit = temp % 10;
                int eachDiff = firstDigit - secondDigit;
                if (diff != eachDiff) {
                    return false;
                }
            }
            return true;
        }
        
    }
    
    
    // 유틸성 클래스
    public static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        
        public FastReader() {
            this.br = new BufferedReader(new InputStreamReader(System.in));
        }
        
        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        
        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}
profile
이전 블로그 : https://oth3410.tistory.com/

0개의 댓글