Java code that meets these requirments Rotates the values in a character array l
ID: 3874789 • Letter: J
Question
Java code that meets these requirments
Rotates the values in a character array left by the
* given number of positions, n, and saves it in a string.
* The first n characters are moved to
* the end of the string.
* Therefore, when done, the string has the same length
* as the given array.
*
* For example,
* rotate(['a', 'b', 'c', 'd'], 1) gives "bcda"
* rotate(['a', 'b', 'c', 'd'], 3) gives "dabc"
* rotate(['h', 'e', 'l', 'l', 'o'], 2) gives "llohe"
You can assume that n is non-negative and
* less than the size of the array.
Explanation / Answer
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Y2018.January;
/**
*
* @author sambh
*/
public class Class1 {
public static String rotate(char[] arr, int n) {
String result = "";
for (int i = 0; i < arr.length; i++)
result = result + arr[(i+n)%arr.length];
return result;
}
public static void main(String[] args) {
char arr[] = {'a', 'b', 'c', 'd'};
System.out.println("rotate(['a', 'b', 'c', 'd'], 1) is " + rotate(arr, 1));
System.out.println("rotate(['a', 'b', 'c', 'd'], 1) is " + rotate(arr, 3));
char arr1[] = {'h', 'e', 'l', 'l','o'};
System.out.println("rotate(['h', 'e', 'l', 'l', 'o'], 1) is " + rotate(arr1, 2));
}
}
This is the shortest code i could think of!! I hpe you like the code
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.