728x90
문제
어떤 양의 정수 X의 각 자리가 등차수열을 이룬다면, 그 수를 한수라고 한다. 등차수열은 연속된 두 개의 수의 차이가 일정한 수열을 말한다. N이 주어졌을 때, 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 1,000보다 작거나 같은 자연수 N이 주어진다.
출력
첫째 줄에 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력한다.
예제
입력 | 출력 | |
예제1 | 110 | 99 |
예제2 | 1 | 1 |
예제3 | 210 | 105 |
예제4 | 1000 | 144 |
소스코드
// ver.1 - Scanner
import java.util.Scanner;
public class Main{
static int hansuCount(int n) {
int cnt = 0;
int li[] = new int[n];
for (int i = 1; i < n+1; i++) {
if (i<100) {
cnt++;
} else if(i<1000) {
int num = i;
for (int j = 0; j < i; j++) {
li[j] = num % 10;
num /= 10;
}
if (li[0]-li[1] == li[1]-li[2]) {
cnt++;
}
}
}
return cnt;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
System.out.println(hansuCount(N));
}
}
// ver.1 - BufferReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Main{
static int hansuCount(int n) {
int cnt = 0;
int li[] = new int[n];
for (int i = 1; i < n+1; i++) {
if (i<100) {
cnt++;
} else if(i<1000) {
int num = i;
for (int j = 0; j < i; j++) {
li[j] = num % 10;
num /= 10;
}
if (li[0]-li[1] == li[1]-li[2]) {
cnt++;
}
}
}
return cnt;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(hansuCount(Integer.parseInt(br.readLine())));
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main{
// 한수 개수를 구하는 함수
static int hansuCount(int n) {
int cnt = 0; // 한수 개수
if (n<100) { // 한자리, 두자리수는 그대로 리턴
return n;
} else {
cnt = 99; // 99까지의 개수
if(n==1000){ // 예외처리
n = 999;
}
for (int i = 100; i <= n; i++) {
int hundred = i / 100; // 백의 자리
int ten = (i / 10) % 10; //십의 자리
int one = i % 10; //일의 자리
if ((hundred-ten) == (ten-one)) { // 각자리수가 수열을 이룰경우
cnt++;
}
}
}
return cnt;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(hansuCount(Integer.parseInt(br.readLine())));
}
}
반응형
'Algorithm > Baekjoon (백준)' 카테고리의 다른 글
[백준][자바] 11654번_아스키 코드 (0) | 2021.11.25 |
---|---|
[백준][파이썬] 11654번_아스키 코드 (0) | 2021.11.25 |
[백준][파이썬] 1065번_한수 (0) | 2021.11.17 |
[백준][자바] 4673번_셀프 넘버 (0) | 2021.11.16 |
[백준][파이썬] 4673번_셀프 넘버 (0) | 2021.11.16 |