Related
I am still somewhat of a beginner to Java, but I need help with my code. I wanted to write an Armstrong Number checker.
An Armstrong number is one whose sum of digits raised to the power three equals the number itself. 371, for example, is an Armstrong number because 3^3 + 7^3 + 1^3 = 371.
If I understand this concept correctly, then my code should work fine, but I don't know where I made mistakes. I would appreciate if you could help correct my mistakes, but still kind of stick with my solution to the problem, unless my try is completely wrong or most of it needs to change.
Here is the code:
public class ArmstrongChecker {
boolean confirm = false;
Integer input;
String converter;
int indices;
int result = 1;
void ArmstrongCheck(Integer input) {
this.input = input;
converter = input.toString();
char[] array = converter.toCharArray();
indices = array.length;
result = (int) Math.pow(array[0], indices);
for (int i = 1; i < array.length; i++) {
result = result + (int) Math.pow(array[i], indices);
}
if (result == input) {
confirm = true;
System.out.println(confirm);
} else {
System.out.println(confirm);
}
}
}
For my tries I used '153' as an input. Thank you for your help!
You aren't summing the digits, but the numeric values of the characters representing them. You can convert such a character to its numeric value by subtracting the character '0':
int result = 0;
for(int i = 0; i < array.length; i++) {
result = result + (int) Math.pow(array[i] - '0', indices);
}
Having said that, it's arguably (probably?) more elegant to read the input as an actual int number and iterate its digits by taking the reminder of 10 on each iteration. The number of digits itself can be calculated using a base-10 log.
int temp = input;
int result = 0;
int indices = (int) Math.log10(input) + 1;
while (temp != 0) {
int digit = temp % 10;
result += (int) Math.pow(digit, indices);
temp /= 10;
}
There is a small logical mistake in your code, You're not converting the character to an integer instead you're doing something like
Math.pow('1', 3) -> Math.pow(49, 3) // what you're doing
Math.pow(1, 3) // what should be done
You should first convert the character to the string using any method below
result = (int) Math.pow(array[0],indices);
for(int i = 1;i<array.length;i++) {
result = result + (int) Math.pow(array[i],indices);
}
For converting char to integer
int x = Character.getNumericValue(array[i]);
or
int x = Integer.parseInt(String.valueOf(array[i]));
or
int x = array[i] - '0';
Alternatively
You can also check for Armstrong's number without any conversion, using the logic below
public class Armstrong {
public static void main(String[] args) {
int number = 153, num, rem, res = 0;
num = number;
while (num != 0)
{
rem = num % 10;
res += Math.pow(rem, 3);
num /= 10;
}
if(res == num)
System.out.println("YES");
else
System.out.println("NO");
}
}
For any int >= 0 you can do it like this.
Print all the Armstrong numbers less than 10_000.
for (int i = 0; i < 10_000; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
prints
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
The key is to use Math.log10 to compute the number of digits in the candidate number. This must be amended by adding 1. So Math.log10(923) returns 2.965201701025912. Casting to an int and adding 1 would be 3 digits.
The number of digits is then the power used for computation.
Then it's just a matter of summing up the digits raised to that power. The method short circuits and returns false if the sum exceeds the number before all the digits are processed.
public static boolean isArmstrong(int v) {
if (v < 0) {
throw new IllegalArgumentException("Argument must >= 0");
}
int temp = v;
int power = (int)Math.log10(temp)+1;
int sum = 0;
while (temp > 0) {
sum += Math.pow(temp % 10, power);
if (sum > v) {
return false;
}
temp/= 10;
}
return v == sum;
}
I want to reverse an integer. I have trying by the following code, the problems occurs when the number is so large that its reverse gets larger than the int limit (for example 1534236469), so in that case it returns some garbage integer.
How can I make use of Integer.MIN_VALUE and Integer.MAX_VALUE to check if the reversed number is within the limits?
Note: it must use int variable type only.
int num = 1534236469;
int reverseInt = 0;
int multiplier = 1;
if ( num < 0 ) {
multiplier *= -1;
}
while ( num != 0 ) {
//get the last digit
int digit = num % 10;
//multiply the reverseInt by 10 and then add the last digit
reverseInt = (reverseInt * multiplier) + digit;
multiplier = 10;
num /= 10;
}
//how to fix this.
if (reverseInt < Integer.MIN_VALUE || reverseInt > Integer.MAX_VALUE ) {
System.out.println("Invalid number");
} else {
System.out.println("Reversed integer is " + reverseInt);
}
You just have to make the check before you add the next digit, so you can simply move your check up to the actual calculation. If your current reversed positive number is greater than Integer.MAX_VALUE/10, then you can't add another digit. Likewise with negative numbers.
The only thing I did was move this part of your code up:
if (reverseInt < Integer.MIN_VALUE || reverseInt > Integer.MAX_VALUE ) {
System.out.println("Invalid number");
} else {
then I added the /10 and a return statement, since the program must end when there's an overflow:
public class StackOverflowTest {
public static void main(String[] args) {
int num = -1534236469;
int reverseInt = 0;
int multiplier = 1;
if ( num < 0 ) {
multiplier *= -1;
}
while ( num != 0 ) {
// if this next step will push is into overflow, then stop:
if (reverseInt < Integer.MIN_VALUE/10 || reverseInt > Integer.MAX_VALUE/10) {
System.out.println("Invalid number");
return;
} else {
//get the last digit
int digit = num % 10;
// multiply the reverseInt by 10 and then add the last digit
reverseInt = (reverseInt * multiplier) + digit;
}
multiplier = 10;
num /= 10;
}
System.out.println("Reversed integer is " + reverseInt);
}
}
Alternatively you can treat it as a String, and then simply reverse the String (along with fiddling with the sign):
public class StackOverflowTest {
public static void main(String[] args) {
reverse(1534236469);
System.out.println();
reverse(-153423646);
}
public static void reverse(int num) {
System.out.println("int = " + num);
int number = num < 0 ? -num : num; // remove the sign
String reverse = new StringBuilder(String.valueOf(number)).reverse().toString();
System.out.println("reverse String: " + reverse);
try {
int reversed = Integer.parseInt(reverse);
reversed = num < 0 ? -reversed : reversed; // get back the sign
System.out.println("Reversed integer is " + reversed);
} catch (NumberFormatException ex) {
System.out.println("Invalid number");
}
}
}
Prints:
int = 1534236469
reverse String: 9646324351
Invalid number
int = -153423646
reverse String: 646324351
Reversed integer is -646324351
In Java 8+, change to:
reverseInt = Math.addExact(Math.multiplyExact(reverseInt, multiplier), digit);
The code will now throw ArithmeticException if the result overflows.
Whenever the value of Integer.MAX_VALUE is exceeded, it starts from Integer.MIN_VALUE i.e. Integer.MAX_VALUE + 1 evaluates to Integer.MIN_VALUE. You can use this feature to get the solution you are looking for.
Simply multiply reverseInt in a loop from 1 to 10 and if the value becomes negative, it means that the next value (reverseInt * multiplier) will exceed Integer.MAX_VALUE. Also, you need to add reverseInt * multiplier in a loop to a value from 0 to 9 and if the value becomes negative, it means that the next value (reverseInt * multiplier + digit) will exceed Integer.MAX_VALUE.
public class Main {
public static void main(String[] args) throws InterruptedException {
int num = 1534236469;
boolean valid = true;
int reverseInt = 0;
int multiplier = 1;
if (num < 0) {
multiplier *= -1;
}
while (num != 0) {
// get the last digit
int digit = num % 10;
for (int i = 1; i <= multiplier; i++) {
for (int j = 0; j <= 9; j++) {
if (reverseInt * i < 0 || (reverseInt * i + j) < 0) {
System.out.println("Invalid number");
valid = false;
break;
}
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
// multiply the reverseInt by 10 and then add the last digit
reverseInt = reverseInt * multiplier + digit;
multiplier = 10;
num /= 10;
}
if (valid) {
System.out.println("Reversed integer is " + reverseInt);
}
}
}
Output:
Invalid number
Can anyone explain to me how to reverse an integer without using array or String. I got this code from online, but not really understand why + input % 10 and divide again.
while (input != 0) {
reversedNum = reversedNum * 10 + input % 10;
input = input / 10;
}
And how to do use this sample code to reverse only odd number. Example I got this input 12345, then it will reverse the odd number to output 531.
Java reverse an int value - Principles
Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4
Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50
Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7
Java reverse an int value - Pseudocode:
a. Extract off the rightmost digit of your input number. (1234 % 10) = 4
b. Take that digit (4) and add it into a new reversedNum.
c. Multiply reversedNum by 10 (4 * 10) = 40, this exposes a zero to the right of your (4).
d. Divide the input by 10, (removing the rightmost digit). (1234 / 10) = 123
e. Repeat at step a with 123
Java reverse an int value - Working code
public int reverseInt(int input) {
long reversedNum = 0;
long input_long = input;
while (input_long != 0) {
reversedNum = reversedNum * 10 + input_long % 10;
input_long = input_long / 10;
}
if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
return (int) reversedNum;
}
You will never do anything like this in the real work-world. However, the process by which you use to solve it without help is what separates people who can solve problems from the ones who want to, but can't unless they are spoon fed by nice people on the blogoblags.
I am not clear about your Odd number.
The way this code works is (it is not a Java specific algorithm)
Eg.
input =2345
first time in the while loop
rev=5 input=234
second time
rev=5*10+4=54 input=23
third time
rev=54*10+3 input=2
fourth time
rev=543*10+2 input=0
So the reversed number is 5432.
If you just want only the odd numbers in the reversed number then.
The code is:
while (input != 0) {
last_digit = input % 10;
if (last_digit % 2 != 0) {
reversedNum = reversedNum * 10 + last_digit;
}
input = input / 10;
}
Simply you can use this
public int getReverseInt(int value) {
int resultNumber = 0;
for (int i = value; i !=0; i /= 10) {
resultNumber = resultNumber * 10 + i % 10;
}
return resultNumber;
}
You can use this method with the given value which you want revers.
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
That is the solution I used for this problem, and it works fine.
More details:
num % 10
This statement will get you the last digit from the original number.
num /= 10
This statement will eliminate the last digit from the original number, and hence we are sure that while loop will terminate.
rev = rev * 10 + num % 10
Here rev*10 will shift the value by left and then add the last digit from the original.
If the original number was 1258, and in the middle of the run time we have rev = 85, num = 12 so:
num%10 = 2
rev*10 = 850
rev*10 + num%10 = 852
int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());
import java.util.Scanner;
public class Reverse_order_integer {
private static Scanner scan;
public static void main(String[] args) {
System.out.println("\t\t\tEnter Number which you want to reverse.\n");
scan = new Scanner(System.in);
int number = scan.nextInt();
int rev_number = reverse(number);
System.out.println("\t\t\tYour reverse Number is = \"" + rev_number
+ "\".\n");
}
private static int reverse(int number) {
int backup = number;
int count = 0;
while (number != 0) {
number = number / 10;
count++;
}
number = backup;
int sum = 0;
for (int i = count; i > 0; i--) {
int sum10 = 1;
int last = number % 10;
for (int j = 1; j < i; j++) {
sum10 = sum10 * 10;
}
sum = sum + (last * sum10);
number = number / 10;
}
return sum;
}
}
See to get the last digit of any number we divide it by 10 so we either achieve zero or a digit which is placed on last and when we do this continuously we get the whole number as an integer reversed.
int number=8989,last_num,sum=0;
while(number>0){
last_num=number%10; // this will give 8989%10=9
number/=10; // now we have 9 in last and now num/ by 10= 898
sum=sum*10+last_number; // sum=0*10+9=9;
}
// last_num=9. number= 898. sum=9
// last_num=8. number =89. sum=9*10+8= 98
// last_num=9. number=8. sum=98*10+9=989
// last_num=8. number=0. sum=989*10+8=9898
// hence completed
System.out.println("Reverse is"+sum);
public static void main(String args[]) {
int n = 0, res = 0, n1 = 0, rev = 0;
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter No.: ");
n1 = scan.nextInt(); // String s1=String.valueOf(n1);
int len = (n1 == 0) ? 1 : (int) Math.log10(n1) + 1;
while (n1 > 0) {
rev = res * ((int) Math.pow(10, len));
res = n1 % 10;
n1 = n1 / 10;
// sum+=res; //sum=sum+res;
sum += rev;
len--;
}
// System.out.println("sum No: " + sum);
System.out.println("sum No: " + (sum + res));
}
This will return reverse of integer
Just to add on, in the hope to make the solution more complete.
The logic by #sheki already gave the correct way of reversing an integer in Java. If you assume the input you use and the result you get always fall within the range [-2147483648, 2147483647], you should be safe to use the codes by #sheki. Otherwise, it'll be a good practice to catch the exception.
Java 8 introduced the methods addExact, subtractExact, multiplyExact and toIntExact. These methods will throw ArithmeticException upon overflow. Therefore, you can use the below implementation to implement a clean and a bit safer method to reverse an integer. Generally we can use the mentioned methods to do mathematical calculation and explicitly handle overflow issue, which is always recommended if there's a possibility of overflow in the actual usage.
public int reverse(int x) {
int result = 0;
while (x != 0){
try {
result = Math.multiplyExact(result, 10);
result = Math.addExact(result, x % 10);
x /= 10;
} catch (ArithmeticException e) {
result = 0; // Exception handling
break;
}
}
return result;
}
Java solution without the loop. Faster response.
int numberToReverse;//your number
StringBuilder sb=new StringBuilder();
sb.append(numberToReverse);
sb=sb.reverse();
String intermediateString=sb.toString();
int reversedNumber=Integer.parseInt(intermediateString);
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class intreverse
{
public static void main(String...a)throws Exception
{
int no;
int rev = 0;
System.out.println("Enter The no to be reversed");
InputStreamReader str=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(str);
no=Integer.parseInt(br.readLine().toString());
while(no!=0)
{
rev=rev*10+no%10;
no=no/10;
}
System.out.println(rev);
}
}
public static int reverse(int x) {
boolean negetive = false;
if (x < 0) {
x = Math.abs(x);
negative = true;
}
int y = 0, i = 0;
while (x > 0) {
if (i > 0) {
y *= 10;
}
y += x % 10;
x = x / 10;
i++;
}
return negative ? -y : y;
}
Here is a complete solution(returns 0 if number is overflown):
public int reverse(int x) {
boolean flag = false;
// Helpful to check if int is within range of "int"
long num = x;
// if the number is negative then turn the flag on.
if(x < 0) {
flag = true;
num = 0 - num;
}
// used for the result.
long result = 0;
// continue dividing till number is greater than 0
while(num > 0) {
result = result*10 + num%10;
num= num/10;
}
if(flag) {
result = 0 - result;
}
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return 0;
}
return (int) result;
}
Scanner input = new Scanner(System.in);
System.out.print("Enter number :");
int num = input.nextInt();
System.out.print("Reverse number :");
int value;
while( num > 0){
value = num % 10;
num /= 10;
System.out.print(value); //value = Reverse
}
int convert (int n)
{
long val = 0;
if(n==0)
return 0;
for(int i = 1; n > exponent(10, (i-1)); i++)
{
int mod = n%( (exponent(10, i))) ;
int index = mod / (exponent(10, i-1));
val *= 10;
val += index;
}
if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE)
{
throw new IllegalArgumentException
(val + " cannot be cast to int without changing its value.");
}
return (int) val;
}
static int exponent(int m, int n)
{
if(n < 0)
return 0;
if(0 == n)
return 1;
return (m * exponent(m, n-1));
}
It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.
if((inputNum <= 999999999)&&(inputNum > 0 ))
{
System.out.print("Your number reversed is: ");
do
{
endInt = inputNum % 10; //to get the last digit of the number
inputNum /= 10;
system.out.print(endInt);
}
While(inputNum != 0);
System.out.println("");
}
else
System.out.println("You used an incorrect number of integers.\n");
System.out.println("Program end");
Even if negative integer is passed then it will give the negative integer
Try This...
public int reverse(int result) {
long newNum=0,old=result;
result=(result>0) ? result:(0-result);
while(result!=0){
newNum*=10;
newNum+=result%10;
result/=10;
if(newNum>Integer.MAX_VALUE||newNum<Integer.MIN_VALUE)
return 0;
}
if(old > 0)
return (int)newNum;
else if(old < 0)
return (int)(newNum*-1);
else
return 0;
}
This is the shortest code to reverse an integer
int i=5263;
System.out.println(Integer.parseInt(new StringBuffer(String.valueOf(i) ).reverse().toString()));
123 maps to 321, which can be calculated as 3*(10^2)+2*(10^1)+1
Two functions are used to calculate (10^N). The first function calculates the value of N. The second function calculates the value for ten to power N.
Function<Integer, Integer> powerN = x -> Double.valueOf(Math.log10(x)).intValue();
Function<Integer, Integer> ten2powerN = y -> Double.valueOf(Math.pow(10, y)).intValue();
// 123 => 321= 3*10^2 + 2*10 + 1
public int reverse(int number) {
if (number < 10) {
return number;
} else {
return (number % 10) * powerN.andThen(ten2powerN).apply(number) + reverse(number / 10);
}
}
If the idea is not to use arrays or string, reversing an integer has to be done by reading the digits of a number from the end one at a time. Below explanation is provided in detail to help the novice.
pseudocode :
lets start with reversed_number = 0 and some value for original_number which needs to be reversed.
the_last_digit = original_number % 10 (i.e, the reminder after dividing by 10)
original_number = original_number/10 (since we already have the last digit, remove the last digit from the original_number)
reversed_number = reversed_number * 10 + last_digit (multiply the reversed_number with 10, so as to add the last_digit to it)
repeat steps 2 to 4, till the original_number becomes 0. When original_number = 0, reversed_number would have the reverse of the original_number.
More info on step 4: If you are provided with a digit at a time, and asked to append it at the end of a number, how would you do it - by moving the original number one place to the left so as to accommodate the new digit. If number 23 has to become 234, you multiply 23 with 10 and then add 4.
234 = 23x10 + 4;
Code:
public static int reverseInt(int original_number) {
int reversed_number = 0;
while (original_number > 0) {
int last_digit = original_number % 10;
original_number = original_number / 10;
reversed_number = reversed_number * 10 + last_digit;
}
return reversed_number;
}
It is an outdated question, but as a reference for others
First of all reversedNum must be initialized to 0;
input%10 is used to get the last digit from input
input/10 is used to get rid of the last digit from input, which you have added to the reversedNum
Let's say input was 135
135 % 10 is 5
Since reversed number was initialized to 0
now reversedNum will be 5
Then we get rid of 5 by dividing 135 by 10
Now input will be just 13
Your code loops through these steps until all digits are added to the reversed number or in other words untill input becomes 0.
while (input != 0) {
reversedNum = reversedNum * 10 + input % 10;
input = input / 10;
}
let a number be 168,
+ input % 10 returns last digit as reminder i.e. 8 but next time it should return 6,hence number must be reduced to 16 from 168, as divide 168 by 10 that results to 16 instead of 16.8 as variable input is supposed to be integer type in the above program.
If you wanna reverse any number like 1234 and you want to revers this number to let it looks like 4321. First of all, initialize 3 variables int org ; int reverse = 0; and int reminder ;
then put your logic like
Scanner input = new Scanner (System.in);
System.out.println("Enter number to reverse ");
int org = input.nextInt();
int getReminder;
int r = 0;
int count = 0;
while (org !=0){
getReminder = org%10;
r = 10 * r + getReminder;
org = org/10;
}
System.out.println(r);
}
A method to get the greatest power of ten smaller or equal to an integer: (in recursion)
public static int powerOfTen(int n) {
if ( n < 10)
return 1;
else
return 10 * powerOfTen(n/10);
}
The method to reverse the actual integer:(in recursion)
public static int reverseInteger(int i) {
if (i / 10 < 1)
return i ;
else
return i%10*powerOfTen(i) + reverseInteger(i/10);
}
You can use recursion to solve this.
first get the length of an integer number by using following recursive function.
int Length(int num,int count){
if(num==0){
return count;
}
else{
count++;
return Lenght(num/10,count);
}
}
and then you can simply multiply remainder of a number by 10^(Length of integer - 1).
int ReturnReverse(int num,int Length,int reverse){
if(Length!=0){
reverse = reverse + ((num%10) * (int)(Math.pow(10,Length-1)));
return ReturnReverse(num/10,Length-1,reverse);
}
return reverse;
}
The whole Source Code :
import java.util.Scanner;
public class ReverseNumbers {
int Length(int num, int count) {
if (num == 0) {
return count;
} else {
return Length(num / 10, count + 1);
}
}
int ReturnReverse(int num, int Length, int reverse) {
if (Length != 0) {
reverse = reverse + ((num % 10) * (int) (Math.pow(10, Length - 1)));
return ReturnReverse(num / 10, Length - 1, reverse);
}
return reverse;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
ReverseNumbers reverseNumbers = new ReverseNumbers();
reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), 0));
scanner.close();
}
}
public int getReverseNumber(int number)
{
int reminder = 0, result = 0;
while (number !=0)
{
if (number >= 10 || number <= -10)
{
reminder = number % 10;
result = result + reminder;
result = result * 10;
number = number / 10;
}
else
{
result = result + number;
number /= 10;
}
}
return result;
}
// The above code will work for negative numbers also
Reversing integer
int n, reverse = 0;
Scanner in = new Scanner(System.in);
n = in.nextInt();
while(n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
System.out.println("Reverse of the number is " + reverse);
public static int reverseInt(int i) {
int reservedInt = 0;
try{
String s = String.valueOf(i);
String reversed = reverseWithStringBuilder(s);
reservedInt = Integer.parseInt(reversed);
}catch (NumberFormatException e){
System.out.println("exception caught was " + e.getMessage());
}
return reservedInt;
}
public static String reverseWithStringBuilder(String str) {
System.out.println(str);
StringBuilder sb = new StringBuilder(str);
StringBuilder reversed = sb.reverse();
return reversed.toString();
}
public static int reverse(int x) {
int tmp = x;
int oct = 0;
int res = 0;
while (true) {
oct = tmp % 10;
tmp = tmp / 10;
res = (res+oct)*10;
if ((tmp/10) == 0) {
res = res+tmp;
return res;
}
}
}
public static double reverse(int num)
{
double num1 = num;
double ret = 0;
double counter = 0;
while (num1 > 1)
{
counter++;
num1 = num1/10;
}
while(counter >= 0)
{
int lastdigit = num%10;
ret += Math.pow(10, counter-1) * lastdigit;
num = num/10;
counter--;
}
return ret;
}
I'm trying to sort the digits of an integer of any length in ascending order without using Strings, arrays or recursion.
Example:
Input: 451467
Output: 144567
I have already figured out how to get each digit of the integer with modulus division:
int number = 4214;
while (number > 0) {
IO.println(number % 10);
number = number / 10;
}
but I don't know how to order the digits without an array.
Don't worry about the IO class; it's a custom class our professor gave us.
It's 4 lines, based on a for loop variant of your while loop with a little java 8 spice:
int number = 4214;
List<Integer> numbers = new LinkedList<>(); // a LinkedList is not backed by an array
for (int i = number; i > 0; i /= 10)
numbers.add(i % 10);
numbers.stream().sorted().forEach(System.out::println); // or for you forEach(IO::println)
There's actually a very simple algorithm, that uses only integers:
int number = 4214173;
int sorted = 0;
int digits = 10;
int sortedDigits = 1;
boolean first = true;
while (number > 0) {
int digit = number % 10;
if (!first) {
int tmp = sorted;
int toDivide = 1;
for (int i = 0; i < sortedDigits; i++) {
int tmpDigit = tmp % 10;
if (digit >= tmpDigit) {
sorted = sorted/toDivide*toDivide*10 + digit*toDivide + sorted % toDivide;
break;
} else if (i == sortedDigits-1) {
sorted = digit * digits + sorted;
}
tmp /= 10;
toDivide *= 10;
}
digits *= 10;
sortedDigits += 1;
} else {
sorted = digit;
}
first = false;
number = number / 10;
}
System.out.println(sorted);
it will print out 1123447.
The idea is simple:
you take the current digit of the number you want to sort(let's call it N)
you go through all digits in already sorted number(let's call it S)
if current digit in S is less than current digit in N, you just insert the digit in the current position in S. Otherwise, you just go to the next digit in S.
That version of the algorithm can sort in both asc in desc orders, you just have to change the condition.
Also, I suggest you to take a look at so-called Radix Sort, the solution here takes some ideas from radix sort, and I think the radix sort is the general case for that solution.
I assume you're allowed to use hashing.
public static void sortDigits(int x) {
Map<Integer, Integer> digitCounts = new HashMap<>();
while (x > 0) {
int digit = x % 10;
Integer currentCount = digitCounts.get(digit);
if (currentCount == null) {
currentCount = 0;
}
digitCounts.put(x % 10, currentCount + 1);
x = x / 10;
}
for (int i = 0; i < 10; i++) {
Integer count = digitCounts.get(i);
if (count == null) {
continue;
}
for (int j = 0; j < digitCounts.get(i); j++) {
System.out.print(i);
}
}
}
How to sort a number without use of array, string or sorting api? Well, you can sort a number with following simple steps (if too much to read then see the debugging output below to get an idea of how the sorting is done):
Get the last digit of the number using (digit = number % 10)
Divide number so last digit is gone (number /= 10)
Loop through digits of number (that does not have digit) and check if digit is smallest
If new smaller digit found then replace the digit = smallest digit and keep looking until end
At the end of the loop you have found the smallest digit, store it (store = (store * 10) + digit
Now that you know this is smallest digit, remove this digit from number and keep applying the above steps to remainder number and every time a smaller digit is found then add it to the store and remove digit from number (if digit is repeated in number, then remove them all and add them to store)
I provided a code with two while loops in the main method and one function. The function does nothing but, builds a new integer excluding the digit that is passed to for example I pass the function 451567 and 1 and the function returns me 45567 (in any order, doesn't matter). If this function is passed 451567 and 5 then, it finds both 5 digits in number and add them to store and return number without 5 digits (this avoid extra processing).
Debugging, to know how it sorts the integer:
Last digit is : 7 of number : 451567
Subchunk is 45156
Subchunk is 4515
Subchunk is 451
Subchunk is 45
Subchunk is 4
Smalled digit in 451567 is 1
Store is : 1
Remove 1 from 451567
Reduced number is : 76554
Last digit is : 4 of number : 76554
Subchunk is 7655
Subchunk is 765
Subchunk is 76
Subchunk is 7
Smalled digit in 76554 is 4
Store is : 14
Remove 4 from 76554
Reduced number is : 5567
Last digit is : 7 of number : 5567
Subchunk is 556
Subchunk is 55
Subchunk is 5
Smalled digit in 5567 is 5
Store is : 145
Remove 5 from 5567
Repeated min digit 5 found. Store is : 145
Repeated min digit 5 added to store. Updated store is : 1455
Reduced number is : 76
Last digit is : 6 of number : 76
Subchunk is 7
Smalled digit in 76 is 6
Store is : 14556
Remove 6 from 76
Reduced number is : 7
Last digit is : 7 of number : 7
Smalled digit in 7 is 7
Store is : 145567
Remove 7 from 7
Reduced number is : 0
Ascending order of 451567 is 145567
The sample code is as follow:
//stores our sorted number
static int store = 0;
public static void main(String []args){
int number = 451567;
int original = number;
while (number > 0) {
//digit by digit - get last most digit
int digit = number % 10;
System.out.println("Last digit is : " + digit + " of number : " + number);
//get the whole number minus the last most digit
int temp = number / 10;
//loop through number minus the last digit to compare
while(temp > 0) {
System.out.println("Subchunk is " + temp);
//get the last digit of this sub-number
int t = temp % 10;
//compare and find the lowest
//for sorting descending change condition to t > digit
if(t < digit)
digit = t;
//divide the number and keep loop until the smallest is found
temp = temp / 10;
}
System.out.println("Smalled digit in " + number + " is " + digit);
//add the smallest digit to store
store = (store * 10) + digit;
System.out.println("Store is : " + store);
//we found the smallest digit, we will remove that from number and find the
//next smallest digit and keep doing this until we find all the smallest
//digit in sub chunks of number, and keep adding the smallest digits to
//store
number = getReducedNumber(number, digit);
}
System.out.println("Ascending order of " + original + " is " + store);
}
/*
* A simple method that constructs a new number, excluding the digit that was found
* to b e smallest and added to the store. The new number gets returned so that
* smallest digit in the returned new number be found.
*/
public static int getReducedNumber(int number, int digit) {
System.out.println("Remove " + digit + " from " + number);
int newNumber = 0;
//flag to make sure we do not exclude repeated digits, in case there is 44
boolean repeatFlag = false;
while(number > 0) {
int t = number % 10;
//assume in loop one we found 1 as smallest, then we will not add one to the new number at all
if(t != digit) {
newNumber = (newNumber * 10) + t;
} else if(t == digit) {
if(repeatFlag) {
System.out.println("Repeated min digit " + t + "found. Store is : " + store);
store = (store * 10) + t;
System.out.println("Repeated min digit " + t + "added to store. Updated store is : " + store);
//we found another value that is equal to digit, add it straight to store, it is
//guaranteed to be minimum
} else {
//skip the digit because its added to the store, in main method, set flag so
// if there is repeated digit then this method add them directly to store
repeatFlag = true;
}
}
number /= 10;
}
System.out.println("Reduced number is : " + newNumber);
return newNumber;
}
}
My algorithm of doing it:
int ascending(int a)
{
int b = a;
int i = 1;
int length = (int)Math.log10(a) + 1; // getting the number of digits
for (int j = 0; j < length - 1; j++)
{
b = a;
i = 1;
while (b > 9)
{
int s = b % 10; // getting the last digit
int r = (b % 100) / 10; // getting the second last digit
if (s < r)
{
a = a + s * i * 10 - s * i - r * i * 10 + r * i; // switching the digits
}
b = a;
i = i * 10;
b = b / i; // removing the last digit from the number
}
}
return a;
}
Here is the simple solution :
public class SortDigits
{
public static void main(String[] args)
{
sortDigits(3413657);
}
public static void sortDigits(int num)
{
System.out.println("Number : " + num);
String number = Integer.toString(num);
int len = number.length(); // get length of the number
int[] digits = new int[len];
int i = 0;
while (num != 0)
{
int digit = num % 10;
digits[i++] = digit; // get all the digits
num = num / 10;
}
System.out.println("Digit before sorting: ");
for (int j : digits)
{
System.out.print(j + ",");
}
sort(digits);
System.out.println("\nDigit After sorting: ");
for (int j : digits)
{
System.out.print(j + ",");
}
}
//simple bubble sort
public static void sort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] > arr[j])
{
int tmp = arr[j];
arr[j] = arr[i];
arr[i] = tmp;
}
}
}
}
class SortDigits {
public static void main(String[] args) {
int inp=57437821;
int len=Integer.toString(inp).length();
int[] arr=new int[len];
for(int i=0;i<len;i++)
{
arr[i]=inp%10;
inp=inp/10;
}
Arrays.sort(arr);
int num=0;
for(int i=0;i<len;i++)
{
num=(num*10)+arr[i];
}
System.out.println(num);
}
}
Since the possible elements (i. e. digits) in a number are known (0 to 9) and few (10 in total), you can do this:
Print a 0 for every 0 in the number.
Print a 1 for every 1 in the number.
int number = 451467;
// the possible elements are known, 0 to 9
for (int i = 0; i <= 9; i++) {
int tempNumber = number;
while (tempNumber > 0) {
int digit = tempNumber % 10;
if (digit == i) {
IO.print(digit);
}
tempNumber = tempNumber / 10;
}
}
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int length = 0;
long tem = 1;
while (tem <= n) {
length++;
tem *= 10;
}
int last=0;
int [] a=new int[length];
int i=0;
StringBuffer ans=new StringBuffer(4);
while(n!=0){
last=n%10;
a[i]=last;
n=n/10;
i++;
}
int l=a.length;
for(int j=0;j<l;j++){
for(int k=j;k<l;k++){
if(a[k]<a[j]){
int temp=a[k];
a[k]=a[j];
a[j]=temp;
}
}
}
for (int j :a) {
ans= ans.append(j);
}
int add=Integer.parseInt(ans.toString());
System.out.println(add);
For the input:
n=762941 ------->integer
We get output:
149267 ------->integer
import java.util.*;
class EZ
{
public static void main (String args [] )
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number - ");
int a=sc.nextInt();
int b=0;
for (int i=9;i>=0;i--)
{
int c=a;
while (c>0)
{
int d=c%10;
if (d==i)
{
b=(b*10)+d;
}
c/=10;
}
}
System.out.println(b);
}
}
import java.util.Scanner;
public class asc_digits
{
public static void main(String args[]){
Scanner in= new Scanner(System.in);
System.out.println("number");
int n=in.nextInt();
int i, j, p, r;
for(i=0;i<10;i++)
{
p=n;
while(p!=0)
{
r = p%10;
if(r==i)
{
System.out.print(r);
}
p=p/10;
}
}
}
}
Stream can also be used for this :
public static int sortDesc(final int num) {
List<Integer> collect = Arrays.stream(valueOf(num).chars()
.map(Character::getNumericValue).toArray()).boxed()
.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
return Integer.valueOf(collect.stream()
.map(i->Integer.toString(i)).collect(Collectors.joining()));
}
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
System.out.println(" rever number is= "+reversernum(num));
System.out.println("\n sorted number is= "+sortedNumdesc(num));
}
private static int reversernum(int n1)
{
if(n1<10)
return n1;
int n_reverse=0;
int lastDigit=0;
while(n1>=1)
{
lastDigit=n1%10;
n_reverse=n_reverse*10+lastDigit;
// System.out.println(" n_reverse "+n_reverse);
n1=n1/10;
}
return n_reverse;
}
private static int sortedNumdesc(int num)
{
if(num<10)
return num;
List<Integer> numbers = new LinkedList<>();
for (int i=num ;i>0;i/=10)
numbers.add(i%10);
// numbers.stream().sorted().forEach(System.out:: println);
int sorted_Num=0;
List<Integer> sortednum= numbers.stream().sorted()
.collect(Collectors.toList());
// System.out.println("sorted list "+sortednum);
for(Integer x: sortednum)
sorted_Num=sorted_Num*10+x;
return sorted_Num;
}
}
Can anyone explain to me how to reverse an integer without using array or String. I got this code from online, but not really understand why + input % 10 and divide again.
while (input != 0) {
reversedNum = reversedNum * 10 + input % 10;
input = input / 10;
}
And how to do use this sample code to reverse only odd number. Example I got this input 12345, then it will reverse the odd number to output 531.
Java reverse an int value - Principles
Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4
Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50
Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7
Java reverse an int value - Pseudocode:
a. Extract off the rightmost digit of your input number. (1234 % 10) = 4
b. Take that digit (4) and add it into a new reversedNum.
c. Multiply reversedNum by 10 (4 * 10) = 40, this exposes a zero to the right of your (4).
d. Divide the input by 10, (removing the rightmost digit). (1234 / 10) = 123
e. Repeat at step a with 123
Java reverse an int value - Working code
public int reverseInt(int input) {
long reversedNum = 0;
long input_long = input;
while (input_long != 0) {
reversedNum = reversedNum * 10 + input_long % 10;
input_long = input_long / 10;
}
if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
return (int) reversedNum;
}
You will never do anything like this in the real work-world. However, the process by which you use to solve it without help is what separates people who can solve problems from the ones who want to, but can't unless they are spoon fed by nice people on the blogoblags.
I am not clear about your Odd number.
The way this code works is (it is not a Java specific algorithm)
Eg.
input =2345
first time in the while loop
rev=5 input=234
second time
rev=5*10+4=54 input=23
third time
rev=54*10+3 input=2
fourth time
rev=543*10+2 input=0
So the reversed number is 5432.
If you just want only the odd numbers in the reversed number then.
The code is:
while (input != 0) {
last_digit = input % 10;
if (last_digit % 2 != 0) {
reversedNum = reversedNum * 10 + last_digit;
}
input = input / 10;
}
Simply you can use this
public int getReverseInt(int value) {
int resultNumber = 0;
for (int i = value; i !=0; i /= 10) {
resultNumber = resultNumber * 10 + i % 10;
}
return resultNumber;
}
You can use this method with the given value which you want revers.
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
That is the solution I used for this problem, and it works fine.
More details:
num % 10
This statement will get you the last digit from the original number.
num /= 10
This statement will eliminate the last digit from the original number, and hence we are sure that while loop will terminate.
rev = rev * 10 + num % 10
Here rev*10 will shift the value by left and then add the last digit from the original.
If the original number was 1258, and in the middle of the run time we have rev = 85, num = 12 so:
num%10 = 2
rev*10 = 850
rev*10 + num%10 = 852
int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());
import java.util.Scanner;
public class Reverse_order_integer {
private static Scanner scan;
public static void main(String[] args) {
System.out.println("\t\t\tEnter Number which you want to reverse.\n");
scan = new Scanner(System.in);
int number = scan.nextInt();
int rev_number = reverse(number);
System.out.println("\t\t\tYour reverse Number is = \"" + rev_number
+ "\".\n");
}
private static int reverse(int number) {
int backup = number;
int count = 0;
while (number != 0) {
number = number / 10;
count++;
}
number = backup;
int sum = 0;
for (int i = count; i > 0; i--) {
int sum10 = 1;
int last = number % 10;
for (int j = 1; j < i; j++) {
sum10 = sum10 * 10;
}
sum = sum + (last * sum10);
number = number / 10;
}
return sum;
}
}
See to get the last digit of any number we divide it by 10 so we either achieve zero or a digit which is placed on last and when we do this continuously we get the whole number as an integer reversed.
int number=8989,last_num,sum=0;
while(number>0){
last_num=number%10; // this will give 8989%10=9
number/=10; // now we have 9 in last and now num/ by 10= 898
sum=sum*10+last_number; // sum=0*10+9=9;
}
// last_num=9. number= 898. sum=9
// last_num=8. number =89. sum=9*10+8= 98
// last_num=9. number=8. sum=98*10+9=989
// last_num=8. number=0. sum=989*10+8=9898
// hence completed
System.out.println("Reverse is"+sum);
public static void main(String args[]) {
int n = 0, res = 0, n1 = 0, rev = 0;
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter No.: ");
n1 = scan.nextInt(); // String s1=String.valueOf(n1);
int len = (n1 == 0) ? 1 : (int) Math.log10(n1) + 1;
while (n1 > 0) {
rev = res * ((int) Math.pow(10, len));
res = n1 % 10;
n1 = n1 / 10;
// sum+=res; //sum=sum+res;
sum += rev;
len--;
}
// System.out.println("sum No: " + sum);
System.out.println("sum No: " + (sum + res));
}
This will return reverse of integer
Just to add on, in the hope to make the solution more complete.
The logic by #sheki already gave the correct way of reversing an integer in Java. If you assume the input you use and the result you get always fall within the range [-2147483648, 2147483647], you should be safe to use the codes by #sheki. Otherwise, it'll be a good practice to catch the exception.
Java 8 introduced the methods addExact, subtractExact, multiplyExact and toIntExact. These methods will throw ArithmeticException upon overflow. Therefore, you can use the below implementation to implement a clean and a bit safer method to reverse an integer. Generally we can use the mentioned methods to do mathematical calculation and explicitly handle overflow issue, which is always recommended if there's a possibility of overflow in the actual usage.
public int reverse(int x) {
int result = 0;
while (x != 0){
try {
result = Math.multiplyExact(result, 10);
result = Math.addExact(result, x % 10);
x /= 10;
} catch (ArithmeticException e) {
result = 0; // Exception handling
break;
}
}
return result;
}
Java solution without the loop. Faster response.
int numberToReverse;//your number
StringBuilder sb=new StringBuilder();
sb.append(numberToReverse);
sb=sb.reverse();
String intermediateString=sb.toString();
int reversedNumber=Integer.parseInt(intermediateString);
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class intreverse
{
public static void main(String...a)throws Exception
{
int no;
int rev = 0;
System.out.println("Enter The no to be reversed");
InputStreamReader str=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(str);
no=Integer.parseInt(br.readLine().toString());
while(no!=0)
{
rev=rev*10+no%10;
no=no/10;
}
System.out.println(rev);
}
}
public static int reverse(int x) {
boolean negetive = false;
if (x < 0) {
x = Math.abs(x);
negative = true;
}
int y = 0, i = 0;
while (x > 0) {
if (i > 0) {
y *= 10;
}
y += x % 10;
x = x / 10;
i++;
}
return negative ? -y : y;
}
Here is a complete solution(returns 0 if number is overflown):
public int reverse(int x) {
boolean flag = false;
// Helpful to check if int is within range of "int"
long num = x;
// if the number is negative then turn the flag on.
if(x < 0) {
flag = true;
num = 0 - num;
}
// used for the result.
long result = 0;
// continue dividing till number is greater than 0
while(num > 0) {
result = result*10 + num%10;
num= num/10;
}
if(flag) {
result = 0 - result;
}
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return 0;
}
return (int) result;
}
Scanner input = new Scanner(System.in);
System.out.print("Enter number :");
int num = input.nextInt();
System.out.print("Reverse number :");
int value;
while( num > 0){
value = num % 10;
num /= 10;
System.out.print(value); //value = Reverse
}
int convert (int n)
{
long val = 0;
if(n==0)
return 0;
for(int i = 1; n > exponent(10, (i-1)); i++)
{
int mod = n%( (exponent(10, i))) ;
int index = mod / (exponent(10, i-1));
val *= 10;
val += index;
}
if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE)
{
throw new IllegalArgumentException
(val + " cannot be cast to int without changing its value.");
}
return (int) val;
}
static int exponent(int m, int n)
{
if(n < 0)
return 0;
if(0 == n)
return 1;
return (m * exponent(m, n-1));
}
It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.
if((inputNum <= 999999999)&&(inputNum > 0 ))
{
System.out.print("Your number reversed is: ");
do
{
endInt = inputNum % 10; //to get the last digit of the number
inputNum /= 10;
system.out.print(endInt);
}
While(inputNum != 0);
System.out.println("");
}
else
System.out.println("You used an incorrect number of integers.\n");
System.out.println("Program end");
Even if negative integer is passed then it will give the negative integer
Try This...
public int reverse(int result) {
long newNum=0,old=result;
result=(result>0) ? result:(0-result);
while(result!=0){
newNum*=10;
newNum+=result%10;
result/=10;
if(newNum>Integer.MAX_VALUE||newNum<Integer.MIN_VALUE)
return 0;
}
if(old > 0)
return (int)newNum;
else if(old < 0)
return (int)(newNum*-1);
else
return 0;
}
This is the shortest code to reverse an integer
int i=5263;
System.out.println(Integer.parseInt(new StringBuffer(String.valueOf(i) ).reverse().toString()));
123 maps to 321, which can be calculated as 3*(10^2)+2*(10^1)+1
Two functions are used to calculate (10^N). The first function calculates the value of N. The second function calculates the value for ten to power N.
Function<Integer, Integer> powerN = x -> Double.valueOf(Math.log10(x)).intValue();
Function<Integer, Integer> ten2powerN = y -> Double.valueOf(Math.pow(10, y)).intValue();
// 123 => 321= 3*10^2 + 2*10 + 1
public int reverse(int number) {
if (number < 10) {
return number;
} else {
return (number % 10) * powerN.andThen(ten2powerN).apply(number) + reverse(number / 10);
}
}
If the idea is not to use arrays or string, reversing an integer has to be done by reading the digits of a number from the end one at a time. Below explanation is provided in detail to help the novice.
pseudocode :
lets start with reversed_number = 0 and some value for original_number which needs to be reversed.
the_last_digit = original_number % 10 (i.e, the reminder after dividing by 10)
original_number = original_number/10 (since we already have the last digit, remove the last digit from the original_number)
reversed_number = reversed_number * 10 + last_digit (multiply the reversed_number with 10, so as to add the last_digit to it)
repeat steps 2 to 4, till the original_number becomes 0. When original_number = 0, reversed_number would have the reverse of the original_number.
More info on step 4: If you are provided with a digit at a time, and asked to append it at the end of a number, how would you do it - by moving the original number one place to the left so as to accommodate the new digit. If number 23 has to become 234, you multiply 23 with 10 and then add 4.
234 = 23x10 + 4;
Code:
public static int reverseInt(int original_number) {
int reversed_number = 0;
while (original_number > 0) {
int last_digit = original_number % 10;
original_number = original_number / 10;
reversed_number = reversed_number * 10 + last_digit;
}
return reversed_number;
}
It is an outdated question, but as a reference for others
First of all reversedNum must be initialized to 0;
input%10 is used to get the last digit from input
input/10 is used to get rid of the last digit from input, which you have added to the reversedNum
Let's say input was 135
135 % 10 is 5
Since reversed number was initialized to 0
now reversedNum will be 5
Then we get rid of 5 by dividing 135 by 10
Now input will be just 13
Your code loops through these steps until all digits are added to the reversed number or in other words untill input becomes 0.
while (input != 0) {
reversedNum = reversedNum * 10 + input % 10;
input = input / 10;
}
let a number be 168,
+ input % 10 returns last digit as reminder i.e. 8 but next time it should return 6,hence number must be reduced to 16 from 168, as divide 168 by 10 that results to 16 instead of 16.8 as variable input is supposed to be integer type in the above program.
If you wanna reverse any number like 1234 and you want to revers this number to let it looks like 4321. First of all, initialize 3 variables int org ; int reverse = 0; and int reminder ;
then put your logic like
Scanner input = new Scanner (System.in);
System.out.println("Enter number to reverse ");
int org = input.nextInt();
int getReminder;
int r = 0;
int count = 0;
while (org !=0){
getReminder = org%10;
r = 10 * r + getReminder;
org = org/10;
}
System.out.println(r);
}
A method to get the greatest power of ten smaller or equal to an integer: (in recursion)
public static int powerOfTen(int n) {
if ( n < 10)
return 1;
else
return 10 * powerOfTen(n/10);
}
The method to reverse the actual integer:(in recursion)
public static int reverseInteger(int i) {
if (i / 10 < 1)
return i ;
else
return i%10*powerOfTen(i) + reverseInteger(i/10);
}
You can use recursion to solve this.
first get the length of an integer number by using following recursive function.
int Length(int num,int count){
if(num==0){
return count;
}
else{
count++;
return Lenght(num/10,count);
}
}
and then you can simply multiply remainder of a number by 10^(Length of integer - 1).
int ReturnReverse(int num,int Length,int reverse){
if(Length!=0){
reverse = reverse + ((num%10) * (int)(Math.pow(10,Length-1)));
return ReturnReverse(num/10,Length-1,reverse);
}
return reverse;
}
The whole Source Code :
import java.util.Scanner;
public class ReverseNumbers {
int Length(int num, int count) {
if (num == 0) {
return count;
} else {
return Length(num / 10, count + 1);
}
}
int ReturnReverse(int num, int Length, int reverse) {
if (Length != 0) {
reverse = reverse + ((num % 10) * (int) (Math.pow(10, Length - 1)));
return ReturnReverse(num / 10, Length - 1, reverse);
}
return reverse;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
ReverseNumbers reverseNumbers = new ReverseNumbers();
reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), 0));
scanner.close();
}
}
public int getReverseNumber(int number)
{
int reminder = 0, result = 0;
while (number !=0)
{
if (number >= 10 || number <= -10)
{
reminder = number % 10;
result = result + reminder;
result = result * 10;
number = number / 10;
}
else
{
result = result + number;
number /= 10;
}
}
return result;
}
// The above code will work for negative numbers also
Reversing integer
int n, reverse = 0;
Scanner in = new Scanner(System.in);
n = in.nextInt();
while(n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
System.out.println("Reverse of the number is " + reverse);
public static int reverseInt(int i) {
int reservedInt = 0;
try{
String s = String.valueOf(i);
String reversed = reverseWithStringBuilder(s);
reservedInt = Integer.parseInt(reversed);
}catch (NumberFormatException e){
System.out.println("exception caught was " + e.getMessage());
}
return reservedInt;
}
public static String reverseWithStringBuilder(String str) {
System.out.println(str);
StringBuilder sb = new StringBuilder(str);
StringBuilder reversed = sb.reverse();
return reversed.toString();
}
public static int reverse(int x) {
int tmp = x;
int oct = 0;
int res = 0;
while (true) {
oct = tmp % 10;
tmp = tmp / 10;
res = (res+oct)*10;
if ((tmp/10) == 0) {
res = res+tmp;
return res;
}
}
}
public static double reverse(int num)
{
double num1 = num;
double ret = 0;
double counter = 0;
while (num1 > 1)
{
counter++;
num1 = num1/10;
}
while(counter >= 0)
{
int lastdigit = num%10;
ret += Math.pow(10, counter-1) * lastdigit;
num = num/10;
counter--;
}
return ret;
}