๐Ÿ‘ฉ‍๐Ÿ’ป/JavaScript

[Programmers] JavaScript์—์„œ ๊ฐ€์šด๋ฐ ๊ธ€์ž ๊ฐ€์ ธ์˜ค๊ธฐ (+Java)

ํ•œ๋‚˜ 2021. 1. 25. 14:32

๋ฌธ์ œ

๋‹จ์–ด s์˜ ๊ฐ€์šด๋ฐ ๊ธ€์ž๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ๋งŒ๋“ค์–ด ๋ณด์„ธ์š”. ๋‹จ์–ด์˜ ๊ธธ์ด๊ฐ€ ์ง์ˆ˜๋ผ๋ฉด ๊ฐ€์šด๋ฐ ๋‘๊ธ€์ž๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ์˜ ์˜ˆ "abcde" -> "c"

"qwer" -> "we"

์ฝ”๋“œ

ํ’€์ด

% ์—ฐ์‚ฐ์ž๋Š” ๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ ํ›„ ๋‚˜๋จธ์ง€๋ฅผ ๊ตฌํ•œ๋‹ค. 2๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‚˜๋จธ์ง€ ๊ธธ์ด๊ฐ€ 0์ด๋ผ๋ฉด, ์ฃผ์–ด์ง„ ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” ์ง์ˆ˜์ด๋‹ค.

๋ฌธ์ž์—ด์€ ์ฝ๊ธฐ ์ „์šฉ ๋ฐฐ์—ด์ฒ˜๋Ÿผ ์ทจ๊ธ‰๋˜๊ธฐ ๋•Œ๋ฌธ์—, ์ธ๋ฑ์Šค๋ฅผ ์‚ฌ์šฉํ•ด ํŠน์ • ์œ„์น˜์˜ ๋ฌธ์ž๋ฅผ ์ถ”์ถœํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋ฅผ ์œ„ํ•ด์„œ ์ „์ฒด ๋ฌธ์ž์—ด ๊ธธ์ด๋ฅผ 2๋กœ ๋‚˜๋ˆˆ ํ›„, Math.floor() ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•ด, ์†Œ์ˆ˜์  ์ดํ•˜๋ฅผ ๋ฒ„๋ฆฐ๋‹ค. (๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค๋Š” ํ•ญ์ƒ ์ •์ˆ˜์ด๋‹ค)

 

์‚ผํ•ญ ์—ฐ์‚ฐ์ž๋ฅผ ์จ์„œ ๋ฌธ์ž์—ด ๊ธธ์ด๊ฐ€ ์ง์ˆ˜์ธ ๊ฒฝ์šฐ์—๋Š” ๊ตฌํ•œ ์ธ๋ฑ์Šค-1 ์˜ ์œ„์น˜๋ฅผ ๋”ํ•œ ๋ฌธ์ž์—ด์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

๋ฌธ์ž์—ด์„ ์ž๋ฅด๋Š” ๋Œ€ํ‘œ์ ์ธ ๋ฉ”์†Œ๋“œ ์ค‘์—๋Š” substr()๋„ ์žˆ์œผ๋‚˜, ๊ณต์‹ ๋ฌธ์„œ์— ๋”ฐ๋ฅด๋ฉด ์•„๋ž˜ ๊ฐ™์€ ๊ฒฝ๊ณ  ๋ฉ”์„ธ์ง€๋ฅผ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

 

Warning: Although String.prototype.substr(…) is not strictly deprecated (as in “removed from the Web standards”), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.

 

์œ„ ๋ฌธ์ œ ํ’€์ด๋Š” substring() ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด์„œ ๋”์šฑ ๊ฐ„๋‹จํ•˜๊ฒŒ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.

substring(indexStart, indexEnd) ๋‘ ๊ฐ€์ง€ ์ธ์ˆ˜๋ฅผ ๋ฐ›๋Š”๋‹ค. ์‹œ์ž‘ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ๋ ์ธ๋ฑ์Šค์˜ ๋ฐ”๋กœ ์•ž์ž๋ฆฌ๊นŒ์ง€๋ฅผ ๊ตฌ๊ฐ„์œผ๋กœ ํ•œ๋‹ค. ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์ด ํ™€์ˆ˜์ผ ๊ฒฝ์šฐ์—๋Š” ๋”ฐ๋ผ์„œ ์‹œ์ž‘ ์ธ๋ฑ์Šค์˜ ์œ„์น˜์— ์ž๋ฆฌํ•œ ๋ฌธ์ž ํ•˜๋‚˜๋งŒ ๋ฐ˜ํ™˜์ด ๋œ๋‹ค.

 

ํ™€์ˆ˜์™€ ์ง์ˆ˜์˜ ๋ถ„๊ธฐ๋ฅผ ๋‚˜๋ˆŒ ํ•„์š”๊ฐ€ ์—†์–ด ์ฝ”๋“œ๊ฐ€ ๋”์šฑ ๊น”๋”ํ•ด์ง„๋‹ค.

 

Java์—์„œ์˜ ํ’€์ด

Java์—์„œ๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ JavaScript์—์„œ ์ผ๋˜ substring() ๋ฉ”์„œ๋“œ๋ฅผ ๋™์ผํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ๊ตฌํ•  ๋•Œ Java๋Š” length() ๋ฉ”์†Œ๋“œ๋ฅผ ์“ด๋‹ค.

 

๋ฌธ์ž์—ด ์ค‘ ๋ฌธ์ž ํ•˜๋‚˜๋งŒ ์ถ”์ถœํ•˜๊ณ  ์‹ถ์„ ๋•Œ๋Š” "๋ฌธ์ž์—ด".charAt(index) ๋ฉ”์†Œ๋“œ๋ฅผ ์“ธ ์ˆ˜๋„ ์žˆ๋‹ค. char ํƒ€์ž…์€ String์œผ๋กœ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•  ๋•Œ๋Š” ํ˜•๋ณ€ํ™˜์„ ํ•ด์ฃผ์–ด์•ผ ํ•˜๋ฏ€๋กœ String.valueOf() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.