Shifting characters interview question within the range
public class ShiftingCharacters {
public final char min;
public final char max;
public final int size;
public static ShiftingCharacters inclusive(char min, char max) {
return new ShiftingCharacters(min, max);
}
ShiftingCharacters(char min, char max) {
this.min = min;
this.max = max;
size = max - min + 1;
}
/** Shift c up by i places, wrapping around to the
* beginning of the range when it reaches the end. */
public char shift(char c, int i) {
return (char) (min + mod(c - min + i, size));
}
/** x mod a */
static int mod(int x, int a) {
return ((x % a) + a) % a;
}
public static void main(String[] args) {
ShiftingCharacters r = ShiftingCharacters.inclusive('a', 'z');
System.out.println(r.shift('z', 2));
}
}
Coding looks good i faced this interview question thanks Ramu for your hard work on providing like this programmes
ReplyDeleteThanks
Delete