알고리즘 문제
코딩테스트 연습1 : 프로그래머스 자릿수구하기
코딩테스트 연습2 : 코드업 자릿수 계산
import java.util.Scanner;
public class SumOfDigit {
public int solutionA(String strNum) {
int result = 0;
for (int i = 0; i < strNum.length(); i++) {
result += Integer.parseInt(String.valueOf(strNum.charAt(i)));
}
return result;
}
// 몫과 나머지 연산자를 활용해보기
public int solutionB(int num) {
int result = 0;
// for문이 아니라 while 사용
while (num > 0) {
// 나머지를 먼저 구해야한다
result += num % 10;
num /= 10;
System.out.printf("result: %d, num: %d \n", result, num);
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SumOfDigit sod = new SumOfDigit();
// String strNum = sc.nextLine();
/*int resultA = sod.solutionA(strNum);
System.out.println(resultA);*/
int num = sc.nextInt();
int resultB = sod.solutionB(num);
System.out.println(resultB);
}
}
Java
복사
solution A (형변환)
1.
String 타입의 숫자를 입력받는다.
2.
strNum 변수의 각각 인덱스의 value값을 int타입으로 바꾸어 result 값에 담는다.
solution B (몫과 나머지 연산자 활용)
1.
int 타입의 숫자를 입력받는다.
2.
입력받은 값 num을 계속 10으로 나누어서 나머지는 result 값에 계속 더하고, 몫은 num값으로 재할당해준다.
cnt(계산횟수) | num | result |
0 | 123 | 0 |
1 | 12 | 3 |
2 | 1 | 5 |
3 | 0 | 6 |
for문이 아니라 while문을 사용한 이유는 계산횟수가 num의 숫자길이에 따라 다르기 때문
—> 몇번을 반복해야할지 정해지지 않아서