코딩테스트

코딩테스트 풀이 - 이어 붙인 수 | 문자열을 숫자로 형 변환하는 방법

히새 2023. 11. 8. 13:53

반복문을 돌려서 나머지 연산자로 홀짝을 판별해 홀수면 odd 에 문자열로 추가, 짝수면 even 에 문자열로 추가해준다.

더한 값을 반환한다.

 

 

odd 와 even 변수에 문자열로 담아주었는데 그대로 더하니까 문자열이 나왔다.

odd + even 을 숫자로 형 변환해서 반환해주도록 하자!

 

맨 위 코드에서 짝수 even += 로 잘못적어서 짝수가 하나만 나왔다. 수정 완료

 


 

🎈 문자열을 숫자로 형 변환하는 방법

 

 

- parseInt()

- Number()

const hurry = '82';
console.log(typeOf(hurry)) 	// string

console.log(Number(hurry)) 	// number
console.log(parseInt(hurry)) 	// number

 

- 연산하기 : 더하기, 1 곱하기, 1 나누기, 0 빼기

const change = "11";

console.log(+change);		// 11
console.log(change *1);		// 11
console.log(change / 1);	// 11
console.log(change - 0);	// 11

 

- Math : floor(), ceil(), round()

const math = "12.5";

console.log(Math.floor(math));	// 12
console.log(Math.ceil(math));	// 13
console.log(Math.round(math));	// 13

 

정수를 내림, 올림, 반올림해준다. 소수점까지 필요할 때에는 다른 방법으로 형변환 하는것이 좋겠다.