내가 생각한 코드
class Solution {
public boolean solution(int x) {
int result = 0;
String str = String.valueOf(x);
for (int i = 0; i < str.length(); i++) {
result += str.parseInt();
if (result % x == 0) {
return true;
} else {
return false;
}
}
}
}
parseInt() 사용법 오류result += str.parseInt(); // 컴파일 에러
parseInt() 는 String 클래스의 인스턴스 메서드가 아닌
Integer 클래스의 static 메서드다
그래서 쓸려면 Integer.parseInt(문자열)
for (int i = 0; i < str.length(); i++) {
result += str.parseInt(); // 전체 문자열을 계속 변환
}
각 자릿수를 따로 더해야하는데, 전체 문자열에 parseInt() 를 적용
if (result % x == 0) {
return true;
} else {
return false;
}
첫 번째 자릿수만 더하고 바로 판단함. 모든 자릿수를 다 더한 후 판단 해야함
class Solution {
public boolean solution(int x) {
int sum = 0; // 자릿수 합
String str = String.valueOf(x);
// 각 자릿수를 개별적으로 더하기
for (int i = 0; i < str.length(); i++) {
sum += Character.getNumericValue(str.charAt(i));
}
// 모든 자릿수를 다 더한 후에 판단
return x % sum ==0;
}
}
class Solction {
public boolean solution(int x) {
int sum = 0;
int temp = x;
// 각 자릿수를 추출해서 더하기
while (temp > 0) {
sum += temp % 10; // 마지막 자릿수 추출
temp /= 10; // 마지막 자릿수 제거
}
return x % sum == 0;
}
}
// 방법 1: 문자열 사용
String str = String.valueOf(123);
int digit = Character.getNumericValue(str.charAt(0)); // 1
// 방법 2: 수학적 방법
int num = 123;
int lastDigit = num % 10; // 3 (마지막 자릿수)
num = num / 10; // 12 (마지막 자릿수 제거)
// Static 메서드 - 클래스명.메서드명()
Integer.parseInt("123");
Math.max(1, 2);
// 인스턴스 메서드 - 객체.메서드명()
String str = "hello";
str.length();
// ❌ 잘못된 방식
for (...) {
// 계산
if (조건) return true; // 중간에 바로 판단
}
// ✅ 올바른 방식
for (...) {
// 모든 계산을 누적한 후
}
return 조건; // 마지막에 한 번만 판단