코테/프로그래머스
[프로그래머스/Lv. 0] k의 개수
imname1am
2023. 2. 3. 11:26
반응형
내 코드
class Solution {
public int solution(int i, int j, int k) {
int cnt = 0;
String str = "";
for(int t=i ; t<=j ; t++) {
str += Integer.toString(t);
}
cnt = str.length() - str.replace(String.valueOf(k), "").length();
return cnt;
}
}
일단 숫자를 문자열로 변환하고
거기서 원하는 문자 길이를 구하는 거는 아래 글들을 보고 했다.
다른 코드
class Solution {
public int solution(int i, int j, int k) {
int answer = 0;
for (int num = i; num <= j; num++){
int tmp = num;
while (tmp != 0){
if (tmp % 10 == k)
answer++;
tmp /= 10;
}
}
return answer;
}
}
내가 이걸 하고 싶었는데 6번째 줄 int tmp = num;
을 빠뜨려서 실행이 잘 안됐었다.ㅠ
(참고)
문자열에서 특정 문자 개수 구하기
: 전체 문자열 길이 - 특정 문자를 뺀 길이 = 특정 문자만 포함한 길이
[Java] 문자열에서 특정 문자 개수 구하는 3가지 방법
Java 문자열에 포함된 특정 문자의 개수를 구하는 방법 3가지를 알아보도록 하겠습니다. 1. 반복문 이용하기 코드 public class CharCount { public static void main(String[] args) { String str = "apple"; System.out.println(
hianna.tistory.com
[Java] 자바 String 특정 문자열 개수 빠르게 확인하는 방법
2022-09-23 1. 방법 //String 에서 a 라는 문자의 개수를 세는 방법 String abc = "aaaaabbbbcccc"; int aCount = abc.length() - abc.replace("a", "").length(); 위와 같은 방식으로 " 전체 문자열 길이 - (전체 문자열에서 a를 제
seeminglyjs.tistory.com
반응형