import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int value0 = scan.nextInt();
scan.close();
long printValue = (long) value0;
System.out.println(++printValue);
}
}
Swift 4.2
import Foundation
extension Int {
static prefix func ++(_ x: inout Int) -> Int {
x += 1
return x
}
}
let line = readLine()
if line != nil {
if var value = Int(line!) {
print(++value)
}
}
이번 문제는 증감연산자를 사용해보는게 목적인 문제인듯하여
굳이 ++을 사용해봤습니다.
switf 4.2에선 해당 연사자가 디폴트로 존재하지 않기때문에 전위 증감 연산자로 Int에 한해서 사용하도록 추가해봤습니다.
1046 : [기초-산술연산] 정수 세 개 입력받아 합과 평균 출력하기 with Swift
43.콘솔에서 세 개의 정수를 입력받아 합과 평균을 출력하라.
입력 : 1line으로 공백으로 구분되어 3개의 정수가 입력됨 (입력 범위 : -2147483648 ~ -2147483647)
출력:
1line : 세 정수의 합
2line : 세 정수의 평균( 실수, 소수점 둘째 자리에서 반올림하여 첫째 자리까지 출력 )
입력 예시
1 2 3
출력 예시
6
2.0
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] values = new int [3];
for (int i = 0; i < values.length; i++) {
values[i] = scan.nextInt();
}
scan.close();
if(values.length > 2) {
long total = values[0] + values[1] + values[2];
double avg = total / 3.0;
System.out.println(total);
System.out.println(String.format("%.1f", avg));
}
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
let split = line!.split(separator: " ")
if split.count == 3 {
var values = [Int]()
for s in split {
if let value = Int(s) {
values.append(value)
}
}
if values.count == 3 {
let total = values[0] + values[1] + values[2]
let avg = Float(total) / 3.0
print(total)
print(String.init(format: "%.1f", avg))
}
}
}
뭐.. 이런곳에서는 의미는 없습니다만
보통 배열이라던가 반복이라던가 할때 직접적으로 숫자를 써서 위치를 입력받는건 위험한 일입니다.
1041 : [기초-산술연산] 문자 한 개 입력받아 다음 문자 출력하기 with Swift
38. 콘솔에서 영문자 한 개를 입력받아, 입력된 문자의 아스키코드값의 다음에 해당하는 문자를 출력하라.
입력 예시
a
출력 예시
b
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
scan.close();
char [] charArray = line.toCharArray();
if(charArray.length > 0) {
System.out.println((char) (charArray[0] + 1));
}
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
if let printValue = line!.first {
let unicodes = printValue.unicodeScalars
for uni in unicodes {
if let printValue = Unicode.Scalar(uni.value + 1) {
print(printValue)
}
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int value0 = scan.nextInt();
int value1 = scan.nextInt();
scan.close();
if(value1 > 0) {
System.out.println(value0/value1);
}
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
let array = line!.split(separator: " ")
if array.count == 2 {
if let value0 = Int(array[0]), let value1 = Int(array[1]) {
if value1 > 0 {
print(value0/value1)
}
}
}
}
1043 : [기초-산술연산] 정수 두 개 입력받아 나눈 나머지 출력하기 with Swift
40. 콘솔에서 정수 두개(a,b)를 입력 받아 a를 b로 나눈 나머지를 출력하라.
입력범위: 0 ~ 2147483647
입력 예시
1 3
출력 예시
1
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int value0 = scan.nextInt();
int value1 = scan.nextInt();
scan.close();
if(value1 > 0) {
System.out.println(value0%value1);
}
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
let array = line!.split(separator: " ")
if array.count == 2 {
if let value0 = Int(array[0]), let value1 = Int(array[1]) {
if value1 > 0 {
print(value0%value1)
}
}
}
}
입력 : 한 줄에 공백으로 두개의 정수가 구분되어 입력된다. 입력되는 정수의 범위는 다음과 같다.
입력 범위 : -1073741824 ~ 1073741824
입력 예시
123 -123
출력 예시
0
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int value0 = scan.nextInt();
int value1 = scan.nextInt();
scan.close();
System.out.println(value0 + value1);
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
let valueArray = line!.split(separator: " ")
if valueArray.count == 2 {
if let value0 = Int(valueArray[0]), let value1 = Int(valueArray[1]) {
print((value0 + value1))
}
}
}
이번문제는 읽자마자 아! 많이 하는 실수인 계산시의 중간값이 범위를 오버하는걸 방지하는 문제이구나!
라고 생각했는데 밑의 단 범위는 이것이다 라고 바로 부정당했네요.
잠깐 이야기하자면
int 의 범위내의 입력값과
int의 범위 내의 출력값이 나온다고해도
그 중간값이 int의 범위내에 있다고 생각 할 수 없습니다.
중간식이 단순 연산이라면 금방 눈치를 채겠지만 막 복잡한 식이 들어가면 어느순간에 범위를 넘어서 버릴수도 있습니다.
물론 이러한 문제는 금방 디버깅시에 발견가능하지만 중간값을 생각안하면 디버깅툴에서 알려주는 라인의 오류를 이해를 못할 수 도 있기에
36.콘솔에서 정수 두 개를 입력받아 합을 출력하라. 단 입력 되는 정수의 범위는 다음과 같다.
입력 범위 : −2147483648 ∼ 2147483647
입력: 두 개의 정수가 공백으로 구분되어 한 줄에 입력된다.
입력 예시
2147483647 2147483647
출력 예시
4294967294
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long longValue = 0;
for (int i = 0; i < 2; i++) {
longValue += scan.nextInt();
}
scan.close();
System.out.println(longValue);
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
let valueArray = line!.split(separator: " ")
if valueArray.count == 2 {
if let value0 = Int(valueArray[0]), let value1 = Int(valueArray[1]) {
print( value0 + value1 )
}
}
}
스위프트가 이전 모든 값이 int범위였을때랑 같은 소스다! 잘못한거 아니냐! 라고 말할수 있겠으나
1040 : [기초-산술연산] 정수 한 개 입력받아 부호 바꿔 출력하기 with Swift
37. 콘솔에서 한 개의 정수를 입력받고 부호를 바꿔 출력 하라.
입력 범위:-2147483647 ~ 2147483647
입력 예시:
-1
출력 예시:
1
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int value = scan.nextInt();
scan.close();
System.out.println(-value);
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
if let value = Int(line!) {
print(-value)
}
}
1034 : [기초-출력변환] 8진 정수 한 개 입력받아 10진수로 출력하기 with Swift
31. 콘솔에서 8진수를 한 개 입력받아 10진수로 출력하라.
입력 예시
13
출력 예시
11
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
scan.close();
String clean = line.trim();
System.out.println(trans8to10(clean));
}
static public int trans8to10(String str8Value) {
if(str8Value.length() < 1) {return -1; }
if(!valueCheck(str8Value)) {
return -1;
} else {
char [] numberArray = str8Value.toCharArray();
int p = numberArray.length - 1;
int result = 0;
for (char number : numberArray) {
int val = Integer.valueOf(String.valueOf(number));
result += val * ((int) Math.pow(8, p));
p--;
}
return result;
}
}
static public boolean valueCheck(String target) {
try {
Integer.valueOf(target);
return true;
} catch (Exception e) {
System.out.println("Error : Main.valueCheck() ->" + e.getLocalizedMessage());
return false;
}
}
}
Swift 4.2
import Foundation
func trans8to10(strValue:String) -> Int{
guard Int(strValue) != nil else { return -1 }
var result = 0;
var p:Double = Double(strValue.count - 1)
for number in strValue {
if let val = Int(String(number)) {
result += val * Int(pow(Double(8), p))
}
p -= 1;
}
return result
}
let line = readLine()
if line != nil {
print(trans8to10(strValue: line!))
}
좀 쓸모없는게 들어간거같고 비효율적으로 느껴집니다.
그렇지만 더 생각하기 귀찮아서 넘어가렵니다.
요즘 딱히 일이없어 잔심부름 같은일 외에 기초100문제 포스팅하다보니 어느새 1/3 지점에 도착해버렸습니다.
이번에도 하다가 그만두고 먼 미래로 남겨두겠지 했는데 페이스를 보니 다음 프로젝트가 저한테 할당되기전까지 놀랍게도 100문제까지 갈지도 모르겠다는 생각이 드네요.
1035 : [기초-출력변환] 16진 정수 한 개 입력받아 8진수로 출력하기 with Swift
32. 콘솔에서 16진수 정수 한 개를 입력받고 8진수로 바꾸어 출력하라.
입력 예시
f
출력 예시
17
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
scan.close();
String clean = line.trim();
System.out.println(trans16to8(clean));
}
static public String trans16to8(String str16Value) {
try {
int converted = Integer.valueOf(str16Value, 16);
return String.format("%o", converted);
} catch (Exception e) {
System.out.println("Err : trans16to8 -> " + e.getLocalizedMessage());
return "";
}
}
}
Swift 4.2
import Foundation
func octalTrans(value:Int) -> [Int] {
var flag = value
var result = [Int]()
while flag >= 8 {
result.append(flag % 8)
flag = flag / 8
if flag < 8 { result.append(flag) }
}
result.reverse()
return result
}
func alpaTransNumber(alpa:Character) -> Int? {
switch alpa {
case "a": return 10
case "b": return 11
case "c": return 12
case "d": return 13
case "e": return 14
case "f": return 15
default: return nil
}
}
func trans16to10(strValue:String) -> Int?{
let letters = CharacterSet.letters
var result = 0;
var p:Double = Double(strValue.count - 1)
for number in strValue.unicodeScalars {
if letters.contains(number) {
if let val = alpaTransNumber(alpa: Character(number)) {
result += val * Int(pow(Double(16), p))
} else {
print("Err : trans16to10 -> 잘못된 값이 입력됨")
return nil
}
} else {
if let val = Int(String(number)) {
result += val * Int(pow(Double(16), p))
} else {
print("Err : trans16to10 -> 잘못된 값이 입력됨")
return nil
}
}
p -= 1;
}
return result
}
let line = readLine()
if line != nil {
if let value = trans16to10(strValue: line!) {
var printValue = String()
for number in octalTrans(value: value) {
printValue += String(number)
}
print(printValue)
}
}
1036 : [기초-출력변환] 영문자 한 개 입력받아 10진수로 출력하기 with Swift
33. 콘솔에서 영문자 한 개 를 입력받아 영문자의 아스키 코드 값을 출력해라.
입력 예시
A
출력 예시
65
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
scan.close();
byte[] bytes = line.getBytes();
for (byte b : bytes) {
System.out.println(b);
}
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
for scalar in line!.trimmingCharacters(in: .whitespacesAndNewlines).unicodeScalars {
print(scalar.value)
}
}
1037 : [기초-출력변환] 정수 한 개 입력받아 아스키 문자로 출력하기 with Swift
34. 콘솔에서 10진 정수 한 개(0~255)를 입력 받아 아스키 문자로 출력해보라.
입력 예시
65
출력 예시
A
JAVA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int ascii_num = scan.nextInt();
scan.close();
System.out.println(String.format("%c", ascii_num));
}
}
Swift 4.2
import Foundation
let line = readLine()
if line != nil {
if let value = Int(line!){
if let uni = Unicode.Scalar(value) {
print(Character.init(uni))
}
}
}