Java Rotate Shift Integer Values Left

Here is a simple method that rotates/shifts the values of an integer to the left by a certain number. The reason why I am using long for the type of the integer is so that the method works with really big numbers. The returned value is the one that has been rotated. Feel free to replace long with int if you are not going to be working with big numbers. Here is the method:

public static long rotateNumber(long d , int rotateBy)

{

String num = Long.toString(d);

int lenght = Long.toString(d).length();

char[] charArray = new char[lenght];

int count = 0;

for (int i = 0; i < lenght; i++) {

if(i < lenght – rotateBy){

charArray[i] = num.charAt(i + rotateBy);

}else{

charArray[i] = num.charAt(count);

count++;

}

}

String newNum =  new String(charArray);

return Long.valueOf(newNum);

}

public static long rotateNumber(long d , int rotateBy)
{
String num = Long.toString(d);
int lenght = Long.toString(d).length();
char[] charArray = new char[lenght];
int count = 0;
for (int i = 0; i < lenght; i++) {
if(i < lenght – rotateBy){
charArray[i] = num.charAt(i + rotateBy);
}else{
charArray[i] = num.charAt(count);
count++;
}
}
String newNum =  new String(charArray);
return Long.valueOf(newNum);
}
Bookmark and Share

Leave a Reply


You must be logged in to comment.