CodingSpace

[HackerRank/Algorithms] Implementation - Repeated String 본문

HackerRank/Algorithm

[HackerRank/Algorithms] Implementation - Repeated String

개발자_조이킴 2022. 9. 1. 21:35

Problem. Implementation - Repeated String


Link.

https://www.hackerrank.com/challenges/repeated-string/problem?isFullScreen=true 

 

Repeated String | HackerRank

Find and print the number of letter a's in the first n letters of an infinitely large periodic string.

www.hackerrank.com


Description.

There is a string, s, of lowercase English letters that is repeated infinitely many times.

Given an integer, n, find and print the number of letter a's in the first n letters of the infinite string.


Key Point. 


My Answer. 

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the 'repeatedString' function below.
 *
 * The function is expected to return a LONG_INTEGER.
 * The function accepts following parameters:
 *  1. STRING s
 *  2. LONG_INTEGER n
 */

function repeatedString(s, n) {
    // Write your code here
    let cntA = 0;
    let result = 0;
    let remain = 0;
    
    for(let i = 0; i < s.length; i++) {
        if(s[i] === 'a')
            cntA = cntA + 1;
    }
    
    let multiply = Math.floor(n / s.length);
    result = cntA * multiply;
    remain = n - (s.length * multiply);
    
    
    for(let i = 0; i < remain; i++) {
        if(s[i] === 'a')
            result = result + 1;
    }
    
    return result;
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const s = readLine();

    const n = parseInt(readLine().trim(), 10);

    const result = repeatedString(s, n);

    ws.write(result + '\n');

    ws.end();
}

References. 

 

Comments