Skip to content

Commit a032648

Browse files
author
Mohamed Sayed-ElMedany
committed
..
1 parent 8ad694f commit a032648

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package javarevisited.top.fifty.java.programs.from.coding.interviews;
2+
3+
import java.util.Scanner;
4+
5+
/**
6+
* @author medany
7+
*/
8+
9+
/*
10+
* Simple Java program to reverse a number in Java using loop and operator This
11+
* program also shows example of using division operator(/) and Remainder
12+
* Operator(%)
13+
*/
14+
15+
public class ReverseaNumber {
16+
public static void main(String args[]) {
17+
Scanner in = new Scanner(System.in);
18+
int num = in.nextInt();
19+
in.close();
20+
System.out.println("Reverse of number: " + num + " is " + reveerse(num));
21+
22+
}
23+
24+
public static Integer reverse(Integer num) {
25+
int reverse = 0;
26+
int remainder = 0;
27+
do {
28+
remainder = num % 10;
29+
reverse = reverse * 10 + remainder;
30+
num = num / 10;
31+
32+
} while (num > 0);
33+
34+
return reverse;
35+
}
36+
37+
public static Integer reveerse(Integer num) {
38+
39+
StringBuilder sb = new StringBuilder(num.toString());
40+
for (int i = 0; i < sb.length() / 2; i++) {
41+
int end = (sb.length() - 1) - i;
42+
char x = sb.charAt(i);
43+
sb.setCharAt(i, sb.charAt(end));
44+
sb.setCharAt(end, x);
45+
}
46+
return Integer.parseInt(sb.toString());
47+
}
48+
}

0 commit comments

Comments
 (0)