Created
September 28, 2021 14:52
-
-
Save OlabodeAbesin/e81fcbd943579b0e2bd26c5f4a33e0d9 to your computer and use it in GitHub Desktop.
Given a string str consisting of letters only and an integer n, the task is to replace every character of the given string by a character which is n times more than it. If the letter exceeds ‘z’, then start checking from ‘a’ in a cyclic manner. Examples: Input: str = “abc”, n = 2 Output: cde a is moved by 2 times which results in character c b i…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// PHP program to move every character | |
// n times ahead in a given string | |
// Function to move string character | |
function encode($s, $n) | |
{ | |
// changed string | |
$newS = ""; | |
// iterate for every characters | |
for($i = 0; $i < strlen($s); ++$i) | |
{ | |
// ASCII value | |
$val = ord($s[$i]); | |
// store the duplicate | |
$dup = $n; | |
// if k-th ahead character exceed 'z' | |
if($val + $n > 122) | |
{ | |
$n -= (122 - $val); | |
$k = $n % 26; | |
$newS = $newS.chr(96 + $n); | |
} | |
else | |
$newS = $newS.chr($val + $n); | |
$n = $dup; | |
} | |
// print the new string | |
echo $newS; | |
} | |
$str = "abc"; | |
$n = 28; | |
// function call | |
encode($str, $k); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment