Java로 작성..
1.먼저 떠오르는건 그냥 잘라붙이기
public int reverseNo1(int num) {
int input = num;
int reversed= 0;
final int scale= 10;
while(input%scale>0) {
reversed *= scale;
reversed = reversed + input%scale;
input /= scale;
}
return reversed;
}
2.배열 인덱스를 거꾸로 저장
public int reverseNo2(int num) {
String input= String.valueOf(num);
char[] reversedChar= new char[input.length()];
for(int i=0;i<input.length();i++) {
reversedChar[input.length-i-1]= input.charAt(i);
}
return Integer.parseInt(new String(reversedChar));
}
3.루프를 반만 돌면서 swap
public int reverseNo3(int num) {
char[] numChars= String.valueOf(num).toCharArray();
int range= numChars.length;
for(int i=0;i<range/2;i++) {
char temp= numChars[i];
numChars[i]= numChars[range-i-1];
numChars[range-i-1]= temp;
}
String stringNum= new String(numChars);
return Integer.parseInt(stringNum);
}
4.제일 뻘짓;; Arrays의 소트 함수를 이용. 배보다 배꼽이..
public int reverseNo4(int num) {
char[] numChars= String.valueOf(num).toCharArray();
CharBox[] charBoxes= new CharBox[numChars.length];
for(int i=0;i<numChars.length;i++) {
charBoxes[i]= new CharBox(i, numChars[i]);
}
Arrays.sort(charBoxes);
for(int i=0;i<numChars.length;i++) {
numChars[i]= charBoxes[i].getChar();
}
return Integer.parseInt(new String(numChars));
}
class CharBox implements Comparable<CharBox> {
int order;
char inputChar;
public CharBox(int order, char ch) {
this.order= order;
this.inputChar= ch;
}
public char getChar() {
return inputChar;
}
public int compareTo(CharBox o) {
if(order>o.order)
return -1;
return 1;
}
}
5.루프를 없애고 리커시브로
public int reverseNo5(int num) {
return reverseByRecursion(num, 0);
}
private int reverseByRecursion(int input, int made) {
if(input==0)
return made;
return reverseByRecursion(input/10, made*10 + input%10);
}
6.String class의 기능을 활용
public int reverseNo6(int num) {
String intput= String.valueOf(num);
String result= "";
for(int i=intput.length();i>0;i--) {
result = intput.charAt(0) + result;
intput= intput.substring(1);
}
return Integer.parseInt(result);
}
7.배열 거꾸로 돌기. 이런 간단한 방법이 있었는데;;
public int reverseNo7(int num) {
String number= String.valueOf(num);
StringWriter sw= new StringWriter();
for(int i= number.length()-1;i>=0;i--) {
sw.write(number.charAt(i));
}
return Integer.parseInt(sw.toString());
}
8.스택을 이용
public int reverseNo8(int num) {
Stack<Character> stack= new Stack<Character>();
char[] chars= String.valueOf(num).toCharArray();
for(char c : chars) {
stack.push(c);
}
StringWriter sw= new StringWriter();
while(stack.size()>0) {
sw.write(stack.pop());
}
return Integer.parseInt(sw.toString());
}
9. Collections 클래스를 이용
public int reverseNo9(int num) {
String[] strings= String.valueOf(num).split("");
List<String> list= Arrays.asList(strings);
Collections.reverse(list);
StringWriter sw= new StringWriter();
for (String string : list) {
sw.write(string);
}
return Integer.parseInt(sw.toString());
}