2020. 5. 2. 16:11ㆍ즐거운 코딩
자연수 35를 뒤집으면 53이 되고, 각 자릿수를 합하면 8이 된다. 또, 1200을 뒤집으면 21이 되고, 각 자릿수를 합하면 3이 된다. 즉, 뒤집었을 때 불필요한 0은 무시된다.
자연수 N이 입력되면 그 수를 뒤집은 수와 각 자릿수의 합을 출력하는 프로그램을 작성하시오.
ex)
input : 123400
output : 4321
10
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
sc.close();
String[] str = n.trim(). split("");
String [] str1 = new String [str.length];
for ( int i = 0; i < str.length; i++ ) {
str1 [i] = str [str.length-i-1];
}
// +++이상 없음+++
int [] arr = new int [str1.length];
for ( int i = 0; i < str1.length; i++ ) {
arr [i] = Integer.parseInt(str1 [i]);
}
// +++이상 없음+++
int j = 0;
int count = 0;
while ( j < str.length ) {
if ( arr [j]!= 0 ) {
break;
}
count++;
j++;
}
// +++이상 없음+++
int sum = 0;
for ( int i = count; i < str.length; i++ ) {
sum = sum + arr [i];
System.out.printf("% d", arr [i]);
}
// +++이상 없음+++
System.out.printf("% n% d", sum);
}
}
먼저 입력받은 수를 뒤집어서 나열해주는 코드를 짠 뒤, 불필요한 0을 제거해서 출력하고 각 자릿수의 합을 출력하게 하였다.
'즐거운 코딩' 카테고리의 다른 글
게시판 프로그램 수정2 (0) | 2020.05.08 |
---|---|
게시판 프로그램 수정1 (0) | 2020.05.07 |
자바 콘솔 게시판 프로그램 (0) | 2020.05.07 |
[JAVA]조건이 있는 석차 프로그램 (0) | 2020.04.24 |
[JAVA]시저 암호 프로그램 (0) | 2020.04.17 |