Related
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.
Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.
import java.util.Scanner;
public class A5E4 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter an integer: ");
int friendlyNumber = in.nextInt();
boolean result = isFriendly(friendlyNumber);
if (result)
{
System.out.println("The integer is friendly");
}
else
{
System.out.println("The integer is not friendly");
}
}
public static boolean isFriendly(int number)
{
int counter = 1;
while (number / 10 >= 1)
{
counter ++;
number = number / 10;
}
boolean check = true;
for (int i = 1; i <= counter; i++)
{
if (number / Math.pow(10, (counter - i)) % i == 0 && check)
{
check = true;
}
else
{
check = false;
}
}
return check;
}
}
while (number / 10 >= 1){
counter ++;
number = number / 10;
}
In this bit, you are reducing number to something smaller than 10. That is probably not what you want. You should make a copy of number here.
Also, proper software design would recommend that you extract this to a dedicated method.
private int countDigits(int number){
if(number < 1) throw new IllegalArgumentException();
int n = number;
int counter = 1;
while (n / 10 >= 1){
counter ++;
n = n / 10;
}
return counter;
}
You need to copy the number which you use to find out how much digits your number has. Otherwise you change the number itself and don't know anymore what it was.
The second mistake is that you divide an integer by Math.pow() which returns a double. So your result is double. You want to have an integer to use the modulo operator.
public static boolean isFriendly(int number)
{
int counter = 1;
int tmpNumber = number;
while (tmpNumber / 10 >= 1)
{
counter ++;
tmpNumber = tmpNumber / 10;
}
boolean check = true;
for (int i = 1; i <= counter; i++)
{
if ((int)(number / Math.pow(10, (counter - i))) % i == 0 && check)
{
check = true;
}
else
{
check = false;
}
}
return check;
}
The first problem is that you are modifying the value of the number you are trying to check. So, if your method is called with 149, then after the while loop to count the digits, its value will be 1. So, you are always going to find that it is 'unfriendly'. Assuming you fix this so that number contains the number you are checking. Try this instead of your 'for' loop:
while ( counter && !( ( number % 10 / counter ) % counter ) )
{
number = number / 10;
counter--;
}
It works by taking the last digit of your number using the modulus or remainder operator and then divides this by the digit position and checks that the remainder is zero. If all is good, it decrements the counter until it reaches zero, otherwise it terminates before counter is zero.
Try something like this (change your isFriendly() method):
public static boolean isFriendly(int number)
{
String numberAsString = String.valueOf(number); //Convert the int as a String to make it easier to iterate through
for(int i = 0; i < numberAsString.length(); i++) {
int currentDigit = Character.getNumericValue(numberAsString.charAt(numberAsString.length() - i - 1)); //Iterate over the number backwards
System.out.println(currentDigit); //Print the current digit
if(currentDigit % (i + 1) != 0) {
return false;
}
}
return true;
}
The easy way is to convert to string and then check if it is friendly:
public static boolean isFriendly(int number)
{
String num = Integer.toString(number);
for (int i = 0, dividedBy = 1; i < num.length(); i++, dividedBy++)
{
String numToCheck = "";
for (int j = 0; j <= i; j++)
{
numToCheck += num.charAt(j);
}
if (Integer.valueOf(numToCheck) % dividedBy != 0) {
return false;
}
}
return true;
}
In our directions, we have to get a 16 digit number, then sum all the digits in the odd place from right to left. After that, we have to sum all the even place digits from right to left, double the sum, then take module 9. When I try to run my code, I keep getting "Invalid", even if it is with a valid credit card number.
public static boolean validateCreditCard(long number) {
double cardSum = 0;
for (int i = 0; i < 16; i++) {
long cardnumber = (long) Math.pow(10, i);
double oddPlaceSum = 0;
double evenPlaceSum = 0;
if (i % 2 != 0) {
oddPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i))));
} else { // so if i%2 ==0
evenPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i)) * 2 % 9));
}
cardSum += evenPlaceSum + oddPlaceSum;
}
if (cardSum % 10 == 0) {
return true;
System.out.println("Valid");
} else {
return false;
System.out.println("Invalid");
}
}
Try this instead :
Convert the 16 digit number into a String using Long.toString(number).
Iterate through the String character by character and keep track of even and odd indexes.
Convert each char to an Integer using Integer.valueOf() thereby adding them incrementally.
Voila, you got your evenSum and oddSum. Next steps should be trivial.
public static boolean validateCreditCard(long number){
String x = Long.toString(number);
int evenSum = 0;
int oddSum = 0;
for(int i=0; i<x.length; i=i+2) {
oddSum += Integer.valueOf(s[i]);
evenSum += Integer.valueOf(s[i+1]);
}
//Do the next steps with odd and even sums.
Also, do handle IndexOutOfBoundsException as appropriate.
You can do it in a single while loop as digits are fixed, like this:
int digit,evensum,oddsum;
int i=16;
while(i > 0){
digit=number%10;
if(i%2 == 0)
evensum+=digit;
else
oddsum+=digit;
i--;
digit/=10;
}
Try this instead
using Recusion find sum of even placed of digit and sum of odd placed of digit.
class Recursion {
static int count = 0;
static int even =0;
static int odd =0;
public static int Digits(int num) {
if (num > 0) {
count++;
if(count%2 == 0){
even += num%10;
}
else{
odd += num%10;
}
Digits(num / 10);
}
return even;
// for odd
// return odd;
}
public static void main(String[] args) {
int num = 31593;
int res = Digits(num);
System.out.println("Total digits are: " + res);
}
}
Help me How to print both even and odd sum together?
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;
}
What I am trying to do should be pretty easy, but as I'm new to java, I'm struggling with what might be basic programming.
The main issue is how to check if the (x+1) number of an integer is greater than the x number, which I am trying to do as follow :
for( int x=0; x < Integer.toString(numblist).length();x++) {
if (numblist[x] < numblist[x+1]) {
compliance= "OK";
} else{
compliance="NOK";
}
But it returns an error "array required but integer found".
It seems to be a basic type mistake, which might come from the previous step (keeping only the numbers included in a string):
for (int p = 0; p < listWithoutDuplicates.size(); p++) {
Integer numblist = Integer.parseInt(listWithoutDuplicates.get(p).getVariantString().replaceAll("[\\D]", ""));
I can't find the answer online, and the fact that it shouldn't be complicated drives me crazy, I would be grateful if someone could help me!
Do the reverse. If they are increasing starting from the first digit, it means that they are decreasing from the last to the first. And it is much easier to program this way:
public boolean increasingDigits(int input)
{
// Deal with negative inputs...
if (input < 0)
input = -input;
int lastSeen = 10; // always greater than any digit
int current;
while (input > 0) {
current = input % 10;
if (lastSeen < current)
return false;
lastSeen = current;
input /= 10;
}
return true;
}
You can't index an integer (i.e. numblist) using the [] syntax -- that only works for arrays, hence your error. I think you're making this more complicated than it has to be; why not just start from the back of the integer and check if the digits are decreasing, which would avoid all this business with strings:
int n = numblist;
boolean increasing = true;
while (n > 0) {
int d1 = n % 10;
n /= 10;
int d2 = n % 10;
if (d2 > d1) {
increasing = false;
break;
}
}
One way I could think of was this:
boolean checkNumber(int n) {
String check = String.valueOf(n); // Converts n to string.
int length = check.length(); // Gets length of string.
for (int i = 0; i < length-1; i++) {
if(check.charAt(i) <= check.charAt(i+1)) { // Uses the charAt method for comparison.
continue; // if index i <= index i+1, forces the next iteration of the loop.
}
else return false; // if the index i > index i+1, it's not an increasing number. Hence, will return false.
}
return true; // If all digits are in an increasing fashion, it'll return true.
}
I'm assuming that you're checking the individual digits within the integer. If so, it would be best to convert the Integer to a string and then loop though the characters in the string.
public class Test {
public static void main(String[] args) {
Integer num = 234; // New Integer
String string = num.toString(); // Converts the Integer to a string
// Loops through the characters in the string
for(int x = 0; x < string.length() - 1; x++){
// Makes sure that both string.charAt(x) and string.charAt(x+1) are integers
if(string.charAt(x) <= '9' && string.charAt(x) >= '0' && string.charAt(x+1) <= '9' && string.charAt(x+1) >= '0'){
if(Integer.valueOf(string.charAt(x)) < Integer.valueOf(string.charAt(x+1))){
System.out.println("OK");
}else{
System.out.println("NOK");
}
}
}
}
}
I think a simple way could be this
package javacore;
import java.util.Scanner;
// checkNumber
public class Main_exercise4 {
public static void main (String[] args) {
// Local Declarations
int number;
boolean increasingNumber=false;
Scanner input = new Scanner(System.in);
number = input.nextInt();
increasingNumber = checkNumber(number);
System.out.println(increasingNumber);
}
public static boolean checkNumber(int number) {
boolean increasing = false;
while(number>0) {
int lastDigit = number % 10;
number /= 10;
int nextLastDigit = number % 10;
if(nextLastDigit<=lastDigit) {
increasing=true;
}
else {
increasing=false;
break;
}
}
return increasing;
}
}
private boolean isIncreasingOrder(int num) {
String value = Integer.toString(num);
return IntStream.range(0, value.length() - 1).noneMatch(i -> Integer.parseInt(value.substring(i, i + 1)) > Integer.parseInt(value.substring(i + 1, i + 2)));
}
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;
}