반복문을 돌려서 나머지 연산자로 홀짝을 판별해 홀수면 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
정수를 내림, 올림, 반올림해준다. 소수점까지 필요할 때에는 다른 방법으로 형변환 하는것이 좋겠다.
'코딩테스트' 카테고리의 다른 글
코딩테스트 풀이 - 마지막 두 원소 (1) | 2023.11.09 |
---|---|
코딩테스트 풀이 - 정수 찾기 | includes() (0) | 2023.11.08 |
코딩테스트 풀이 - 뒤에서 5등까지 | sort() 로 오름차순, 내림차순, slice() (0) | 2023.11.06 |
코딩테스트 풀이 - 배열 만들기 3 | slice() (0) | 2023.11.03 |
코딩테스트 풀이 - 암호 해독 (0) | 2023.11.03 |