728x90
하샤드 수
문제설명
![[programmers] 하샤드 수 - undefined - 하샤드 수 [programmers] 하샤드 수 - undefined - 하샤드 수](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
문제를 보자마자 십의 자리수와 일의 자리수를 어떻게 나누지? 라는 생각을 했었던 것 같다.
내가 알고 있던것은 String 값만 substring으로 나누는것만 알아서 일단 String 으로 바꾸고 시작했던것 같다.
class Solution {
public boolean solution(int x) {
boolean answer = true;
String str = Integer.toString(x);
String[] s =new String[str.length()];
int a=0;
char c ;
for(int i=0;i<str.length();i++){
c=str.charAt(i);
s[i]=Character.toString(c);
a+=Integer.parseInt(s[i]);
if(x%a==0) answer=true;
else answer =false;
}
return answer;
}
}
여기서 받은 수 x를 toString으로 String str 에 넣고 str의 길이만큼 String 배열 s를 만들었다.
str의 길이만큼 반복문을 돌립니다.
c= str.charAt(i) charAt 메소드는 (index) 의 문자를 가져오는데 이걸 char c 에 넣고
이렇게 가져온 하나의 문자를 다시 배열 s에 넣습니다.
문자열 s를 Integer.parseInt 를 하여 int 형 a에 넣어 줍니다 x의 자리수가 2자리수이면 두번째 반복문이 끝났을때의 answer의 값이 return 되게 설계하였습니다.
728x90
'ps' 카테고리의 다른 글
[programmers] 숫자 문자열과 영단어 (0) | 2022.05.10 |
---|---|
[programmers] 신규 아이디 추천 (2) | 2022.05.10 |
상위 n개 레코드 (0) | 2022.05.09 |
핸드폰 번호 가리기 (0) | 2022.05.09 |
x만큼 간격이 있는 n개의 숫자 (0) | 2022.05.08 |
댓글