BOJ::1065 한수

https://www.acmicpc.net/problem/1065


100이상 수부터 자릿수끼리 등차수열인 수를 찾는 문제.

처음풀땐 String형으로 자리수끼리 비교했었는데,

두번째 풀때는 %연산을 이용해 풀었다.

%연산을 이용하는것이 더 깔끔해서 %연산을 이용한 코드를 가져왔다.



JAVA

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
32
33
34
35
36
37
38
39
40
41
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
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 cnt=0;
        for(int i = 1 ; i <= n ; i++){
            if(isCheck(i)){
                cnt++;
            }
        }
        System.out.println(cnt);
    }
    //한수인지 체크
    public static boolean isCheck(int n){
        //1~99까지는 모두 한수이다.
        if(n<100){
            return true;
        }
        //%연산을 통해 각각 자리수끼리의 차이를 비교하였다.
        else{
            int x = n%10;
            n=n/10;
            int y = n%10;
            int diff = x-y;
            while(n>=10){
                n=n/10;
                x = y;
                y = n%10;
                if(diff != x-y){
                    return false;
                }
            }
        }
        return true;
    }
}
cs



C++

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
32
33
34
35
#include <iostream>
using namespace std;
 
bool isCheck(int n) {
    if (n < 100) {
        return true;
    }
    else {
        int x = n % 10;
        n = n / 10;
        int y = n % 10;
        int diff = x - y;
        while (n >= 10) {
            n = n / 10;
            x = y;
            y = n % 10;
            if (diff != x - y) {
                return false;
            }
        }
    }
    return true;
}
 
int main() {
    int n, cnt=0;
    cin >> n;
 
    for (int i = 1; i <= n; i++) {
        if (isCheck(i)) {
            cnt++;
        }
    }
    cout << cnt << endl;
}
cs


'BOJ::문제풀이' 카테고리의 다른 글

1152 단어의 개수  (0) 2017.12.30
1149 RGB거리  (0) 2017.12.30
1049 기타줄  (0) 2017.12.30
1012 유기농배추  (0) 2017.12.30
1009 분산처리  (0) 2017.12.30

+ Recent posts