[Java] 지정한 범위 내에서 특정 숫자가 몇번 들어가는지 세는 방법
728x90
반응형
google 입사시험이라는데

일단 아래와 같이 풀어보았다.

package com.algorithm;
public class AlgoMain {
// 1부터 10,000까지 숫자 8이 총 몇번나오는 카운팅 하세요.
// 8이 포함되어 있는 모든 숫자의 갯수를 카운팅 하는게 아님
public static void main(String[] args) {
int maxnum = 8;
int tarnum = 10000;
System.out.println(numberCount(maxnum, tarnum));
}
public int sum(int num) {
int result = 0;
result = num*(num+1)/2;
return result;
}
public static int numberCount(int max, int target) {
int count = 0;
// 1. target 변수를 String으로 바꾼다.
String tarstr = target + "";
// 2. 검색할 범위만큼 for문을 돌린다.
for (int i = 1; i < max+1; i++) {
// 3. 1부터 차례로 String으로 바꾼다.
String numstr = i + "";
// 4. 2자리 수 이상의 경우에는 숫자를 나누어야 한다.
for (int j = 0; j < numstr.length(); j++) {
// 5. 나눈 숫자와 target이 일치하는지 확인하고
// 맞으면 count를 하나씩 올린다.
if(numstr.charAt(j) == tarstr.charAt(0)){
count++;
System.out.print(numstr+" : ");
System.out.println(">>> "+count);
}
}
}
return count;
}
}


그런데 충격적인 풀이들이 많다.

http://codingdojang.com/scode/393

놀라운 세상이다.

728x90
반응형