1. ๋ฌธ์ œ

OX๋ฌธ์ œ ์‹œํ—˜์—์„œ ์—ฐ์†์ ์œผ๋กœ ๋‹ต์„ ๋งžํžˆ๋Š” ๊ฒฝ์šฐ์—๋Š” ๊ฐ€์‚ฐ์ ์„ ์ฃผ๊ธฐ๋กœ ํ–ˆ๋‹ค. ์•ž์˜ ๋ฌธ์ œ์— ๋Œ€ํ•ด์„œ๋Š” ๋‹ต์„ ํ‹€๋ฆฌ๋‹ค๊ฐ€ ๋‹ต์ด ๋งž๋Š” ์ฒ˜์Œ ๋ฌธ์ œ๋Š” 1์ ์œผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค. ๋˜ํ•œ, ์—ฐ์†์œผ๋กœ ๋ฌธ์ œ์˜ ๋‹ต์ด ๋งž๋Š” ๊ฒฝ์šฐ์—์„œ ๋‘ ๋ฒˆ์งธ ๋ฌธ์ œ๋Š” 2์ , ์„ธ ๋ฒˆ์งธ ๋ฌธ์ œ๋Š” 3์ , ..., K๋ฒˆ์งธ ๋ฌธ์ œ๋Š” K์ ์œผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค. ํ‹€๋ฆฐ ๋ฌธ์ œ๋Š” 0์ ์œผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค. ๋‹ต์ด ๋งž์€ ๋ฌธ์ œ์˜ ๊ฒฝ์šฐ์—๋Š” 1๋กœ ํ‘œ์‹œํ•˜๊ณ , ํ‹€๋ฆฐ ๊ฒฝ์šฐ์—๋Š” 0์œผ๋กœ ํ‘œ์‹œํ•œ๋‹ค. ์ฑ„์  ๊ฒฐ๊ณผ๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ด ์ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

 

์ž…๋ ฅ ์˜ˆ์ œ | 1 0 1 1 1 0 0 1 1 0

์ถœ๋ ฅ ์˜ˆ์ œ | 10

 

 

2. ๋ฌธ์ œํ’€์ด๊ณผ์ •

1. ๋ฐฐ์—ด ํƒ์ƒ‰(for ๋ฐ˜๋ณต๋ฌธ) 

2. ํ•˜๋‚˜์”ฉ ๋Œ๋ฉด์„œ ์ ์ˆ˜๋ฅผ ๋ˆ„์ ํ•ด์ฃผ๋Š”๋ฐ, ๊ฐ€์‚ฐ์ ์„ ๊ฐ™์ด ๋”ํ•˜๋ฉด์„œ ๊ณ„์‚ฐํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. 

 

[์‹œ๋„ 1]

function solution(arr){
	let answer = 0;
    for(let i=0; i<arr.length; i++){
    	if(A[i] === 1){
        	answer += 1;
        } else answer += 0;
     }
     return answer;
}

let A = [1, 0, 1, 1, 1, 0, 0, 1, 1, 0];
console.log(solution(A));

์ฒ˜์Œ์— ์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ๊ฐ€์‚ฐ์  ๊ณ„์‚ฐ์ด ์•ˆ๋˜์–ด์„œ 6์ด ๋‚˜์™”๋‹ค. 

๊ฐ€์‚ฐ์  ๊ณ„์‚ฐ์„ ํ•˜๋ ค๋ฉด ๋ญ”๊ฐ€ ์š”์†Œ๊ฐ€ ๋” ํ•„์š”ํ•œ ๊ฒƒ ๊ฐ™์€๋ฐ ๋ญ˜๊นŒ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€

 

[์‹œ๋„ 2]

function solution(arr){
	let answer = 0;
    let count;
    for(let i=0; i<arr.length; i++){
    	if(A[i] === 1){
        	answer += 1;
            count = answer++;
        } else answer += 0;
     }
     return count;
}

let A = [1, 0, 1, 1, 1, 0, 0, 1, 1, 0];
console.log(solution(A));

count ๋ณ€์ˆ˜๋ฅผ ํ•˜๋‚˜ ๋” ๋งŒ๋“ค์–ด์ค˜์„œ answer+1๊ฐ’์ด count์— ๋ˆ„์ ๋˜๋„๋ก ํ–ˆ๋‹ค. 

๊ทธ๋ ‡์ง€๋งŒ ์•„์ง ๊ณ„์‚ฐ์ด ์ •ํ™•ํžˆ ๋˜์ง€ ์•Š์•˜๋‹ค. 

 

[์‹œ๋„ 3]

function solution(arr){
	let answer = 0;
    let count = 0;
    	for(let i=0; i<arr.length; i++){
        	if(arr[i] === 1){
            	count++; // count = count + 1
                answer+=count; // answer = answer + count // answer์— count๋ˆ„์ 
            } else count=0; // 0์ด ๋“ค์–ด์˜ฌ ๊ฒฝ์šฐ count ์ดˆ๊ธฐํ™” 
         }
    return answer;
}

let A = [1, 0, 1, 1, 1, 0, 0, 1, 1, 0];
console.log(solution(A));

answer์™€ count์— ๋ชจ๋‘ ๋ˆ„์ ์„ ํ•ด์ค˜์•ผํ•˜๋‹ˆ๊นŒ 0์œผ๋กœ ์„ค์ •ํ•ด์ค€๋‹ค. 

count์— ๊ฐ’์„ ๋จผ์ € ๋”ํ•˜๊ณ , answer์— count๋ฅผ ๋”ํ•ด์„œ ๋ˆ„์ ํ•ด์ค€๋‹ค. 

0์ ์ผ ๊ฒฝ์šฐ๋Š” count๋ฅผ ๋‹ค์‹œ 0์œผ๋กœ ๋งŒ๋“ ๋‹ค. 

 

 

for of ๋ฌธ(๋ฐฐ์—ด์˜ ๊ฐ’์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋ฐ˜๋ณต)์„ ์จ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค! 

function solution(arr){
	let answer = 0;
    let count = 0;
    	for(x of arr){
        	if(x === 1){
            	count++; // count = count + 1
                answer+=count; // answer = answer + count
            } else count=0;
         }
    return answer;
}

let A = [1, 0, 1, 1, 1, 0, 0, 1, 1, 0];
console.log(solution(A));

+ Recent posts