본문 바로가기

알고리즘/알고리즘

자릿수 더하기

 

 


 

https://school.programmers.co.kr/learn/courses/30/lessons/12931

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


s.split("")

public class 자릿수더하기 {

	public static void main(String[] args) {
//		N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.
		자릿수더하기.Solution solution = new 자릿수더하기.Solution();
		int result = solution.solution(123);
		System.out.println(result);

	}

	static class Solution {
		public int solution(int n) {
			int answer = 0;
			String s = String.valueOf(n);
			String[] splitedArr = s.split("");

			for (String word : splitedArr) {
				answer += Integer.parseInt(word);
			}

			return answer;
		}
	}
}

 

 

 

 


s.charAt(index) - '0'

public class Three {

	public static void main(String[] args) {
		// N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.
		Three.Solution solution = new Three.Solution();
		int result = solution.solution(123);
		System.out.println(result);  // 출력: 6
	}

	static class Solution {
		public int solution(int n) {
			int answer = 0;

			// 숫자를 문자열로 변환
			String s = String.valueOf(n);

			// 각 문자를 직접 숫자로 변환하여 더하기
			for (int i = 0; i < s.length(); i++) {
				answer += s.charAt(i) - '0'; // ASCII 값을 이용해 숫자로 변환
			}

			return answer;
		}
	}
}

 

 


chars()

Java 8 이상에서는 chars() 메서드를 사용해 문자열의 각 문자를 스트림으로 처리할 수 있습니다.

 
public class Three {

	public static void main(String[] args) {
		// N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.
		Three.Solution solution = new Three.Solution();
		int result = solution.solution(123);
		System.out.println(result);  // 출력: 6
	}

	static class Solution {
		public int solution(int n) {
			// 숫자를 문자열로 변환
			String s = String.valueOf(n);
			
			// chars() 메서드로 각 문자를 스트림 처리하여 합산
			int answer = s.chars()
				.map(Character::getNumericValue)
				.sum();

			return answer;
		}
	}
}

 

 


 

 


 

'알고리즘 > 알고리즘' 카테고리의 다른 글

조이스틱  (0) 2024.08.04
큰 수 만들기  (0) 2024.08.02
N개의 최소공배수  (0) 2024.08.01
최대공약수, 최소공배수  (0) 2024.08.01
[programmers] 숫자 문자열과 영단어  (0) 2022.08.23