Algorithm
백준 11720 / 숫자의 합
코동이
2020. 7. 9. 19:36
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine());
String line = br.readLine();
int res=0;
for(int i=0;i<num;i++) {
res += line.charAt(i)-'0';
}
System.out.println(res);
}
}
char와 int를 서로 변형하는 과정에서 char형의 숫자들은 -'0'을 통해 int형 숫자를 가지게된다.
0(=48)~9까지 숫자가 ASCII코드에서 가장 낮은 쪽이고,
대문자 A(=65)시작,
소문자 a(=97)부터 시작된다는 것을 기억한다.
자바에서는 char형과 int형이 입력됬을 때 기본적으로 int형으로 변환된다. 따라서 char를 반환할지, int를 반환할지 먼저 정해야 한다. int형을 반환받을 것이라면 상관없지만 char형을 반환받을 것이라면 (char)을 잘 붙어주어야 한다.
- 각 자리의 char형 숫자를 int로 변경
String line = "12345678"
//각 숫자를 더하고 싶은 경우
int ans=0;
for(int i=0; i<line.length(); i++){
ans += line.charAt(i) - '0';
}
- 각 자리의 char형 문자열을 대문자로 변경
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String line = "AbCdefg";
String ans="";
for(int i=0;i<line.length();i++){
char a = line.charAt(i);
if( a >= 65+32){
ans += (char)(a - 32);
} else {
ans += a;
}
}
System.out.println(ans);
}
}
- 각 자리의 char형 문자열을 소문자로 변경
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String line = "AbCdefg";
String ans="";
for(int i=0;i<line.length();i++){
char a = line.charAt(i);
if( a < 65+32){
ans += (char)(a + 32);
} else {
ans += a;
}
}
System.out.println(ans);
}
}
반응형