Last active
April 15, 2020 17:50
-
-
Save IngeFrodo/abaaf7bb8de4cda3d5fc5cacc2d9117a to your computer and use it in GitHub Desktop.
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
class PerformStringShifts { | |
public String stringShift(String s, int[][] shift) { | |
int shiftNumber = 0; | |
for (int[] shiftOperation : shift) { | |
if (shiftOperation[0] == 1) { | |
shiftNumber += shiftOperation[1]; | |
} else { | |
shiftNumber -= shiftOperation[1]; | |
} | |
} | |
char[] charArray = s.toCharArray(); | |
shiftNumber %= charArray.length; | |
if (shiftNumber < 0) { | |
shiftNumber += charArray.length; | |
} | |
shiftArray(charArray, shiftNumber); | |
return new String(charArray); | |
} | |
private void shiftArray(char[] charArray, int shiftNumber) { | |
reverse(charArray, 0, charArray.length - 1); | |
reverse(charArray, 0, shiftNumber - 1); | |
reverse(charArray, shiftNumber, charArray.length - 1); | |
} | |
private void reverse(char[] charArray, int left, int right) { | |
while (left < right) { | |
swap(charArray, left++, right--); | |
} | |
} | |
private void swap(char[] charArray, int from, int to) { | |
char c = charArray[from]; | |
charArray[from] = charArray[to]; | |
charArray[to] = c; | |
} | |
} |
Yes, it can be negative the % returns the same sign as the dividend
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nicely done. I like how you created small methods, your code looks very clean.
One minor comment: would the
if
condition in line14
ever be true? As far as I know the module operator will always return a positive value