PR起動パスワード


質問する


過去の解釈を参照


過去の解釈を参照

に答える

  • 以前の解答では,アルファベットをUnicodeに変換して解いた結果,Unicode値が小文字または大文字の範囲を超えていることが分かった.
  • なので今回は、あらかじめ配列に小文字と大文字を定義しておき、パラメータとして受信した文字列の論理を逐字チェックします.
  • まず、所与の文字列の文字が大文字と小文字のどの配列に属するかをチェックします.
  • は、配列内で所定の文字の位置(インデックス)を検索し、nでインデックスを追加する.
  • 加算されたインデックスが配列のサイズを超えている場合、더해진 인덱스 -= 배열 길이でインデックスを配列の先頭から再開します.
  • コード#コード#

    function solution(s, n) {
        const ABC = ["A","B","C","D","E","F","G","H","I","J","K","L",'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        const abc = ABC.map((el) => el.toLowerCase());
        let answer = "";
        const arr = s.split("");
        
        arr.forEach((el) => {
            if(ABC.indexOf(el) !== -1) {
                const idx = ABC.indexOf(el);
                let newIdx = idx + n;
                if(newIdx >= ABC.length) newIdx = newIdx - ABC.length; 
                answer += ABC[newIdx];
            }
            else if(abc.indexOf(el) !== -1) {
                const idx = abc.indexOf(el);
                let newIdx = idx + n;
                if(newIdx >= abc.length) newIdx = newIdx - abc.length; 
                answer += abc[newIdx];
            } else {
                answer += el;
            }
        })
    
        return answer;
    }