Reverse the digits of an integer [duplicate] - java

This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 3 years ago.
I'm a Java beginner so please pardon me if the question seems silly but I already searched the forums but it seems like no one has my problem.
I need to reverse the digits of an integer, and my class hasn't covered while or if loops yet, so I can't use those. All answers I can find on stackoverflow use those, so I can't use those.
the input I am given is below 10000 and above 0 and the code I have written has no problem reversing the integer if the input is 4 digits (e.g. 1000 - 9999) but once the input is between 1 - 999 it creates zeroes on the right hand side but according to the answer sheets its wrong.
For example: 1534 gets turned into 4351, but
403 becomes 3040 instead of the 304 it should be, and 4 becomes 4000 instead of 4.
I've tried different things in the code but it seems to just keep giving the same answer. Or maybe I'm just missing some key mathematics, I'm not sure.
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
value = (value / 10);
int digit2 = (value % 10);
value = (value / 10);
int digit3 = (value % 10);
value = (value / 10);
int digit4 = (value % 10);
String reversednum = ("" + digit + digit2 + digit3 + digit4);
System.out.println ( reversednum);
and
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
int reversednum = (digit);
value = (value /10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value);
reversednum = (reversednum * 10 + digit);
System.out.println (reversednum);
What am I doing wrong?

You can convert from int to String -> reverse String -> convert again in int.
This is a code example.
public int getReverseInt(int value) {
String revertedStr = new StringBuilder(value).reverse().toString();
return Integer.parseInt(revertedStr);
}

Your code assumes that the number can be divided by 1000, which is clearly not the case for numbers below 1000. So add some if statements:
public int reverseNumber(int n) {
// step one: we find the factors using integer maths
int s = n;
int thousands = s / 1000; // this will be 0 if the number is <1000
s = s - thousands*1000;
int hundreds = s / 100; // this will be 0 if the number is <100
s = s - hundreds*100;
int tens = s / 10; // etc.
s = s - tens*10;
int ones = s;
// then: let's start reversing. single digit?
if (n<10) return n;
// two digits?
if (n<100) {
return ones*10 + tens;
}
// etc.
if (n<1000) {
return ones*100 + tens*10 + hundreds;
}
if (n<10000) {
return ones*1000 + tens*100 + hundreds*10 + thousands;
}
// if we get here, we have no idea what to do with this number.
return n;
}

Without spoon-feeding you code (leaving the value of writing your own homework code intact)...
Although you've said you can't use a loop, I don't think there's a sane approach that doesn't use one. Your basic problem is you have hard-coded a solution that works when the number happens to have 4 digits, rather than using code that adapts to a variable length. ie, are not using a loop.
All is not lost with your code however. You have figured out the essence of the solution. You just need to convert it to work processing one digit at a time. Consider using recursion, that divides the number by 10 each time and continues until the number is zero. Of course, you’ll have to capture the end digit before it’s lost by division.
Pseudo code may look like:
pass in the number and the current result
if the number is 0 return result
multiply result by 10 and add remainder of number divided by 10
return the result of calling self with number divided by 10 and result
then call this passing number and zero

Using modulus and division:
int nbr = 123; // reverse to 321 or 3*10*10 + 2*10 + 1
int rev = 0;
while(nbr > 0) {
rev *= 10; // shift left 1 digit
int temp = nbr % 10; // get LO digit
rev += temp; // add in next digit
nbr /= 10; // move to next digit
}
Or a recursive method:
public static int reverseInt(int number, int value) {
switch(number) { // is this conditional statement allowed???
case 0:
return value;
}
value *= 10;
int lod = number % 10;
value += lod;
number /= 10;
return reverseInt(number, value);
}

Related

Java:Three digit Sum - Find out all the numbers between 1 and 999 where the sum of 1st digit and 2nd digit is equal to 3rd digit

Problem statement: Three digit sum - Find all the numbers between 1 and 999 where the sum of the 1st digit and the 2nd digit is equal to the 3rd digit.
Examples:
123 : 1+2 = 3
246 : 2+4 = 6
Java:
public class AssignmentFive {
public static void main(String[] args) {
int i=1;
int valuetwo;
int n=1;
int sum = 0;
int valuethree;
int valueone = 0;
String Numbers = "";
for (i = 1; i <= 999; i++) {
n = i;
while (n > 1) {
valueone = n % 10;/*To get the ones place digit*/
n = n / 10;
valuetwo = n % 10;/*To get the tens place digit*/
n = n / 10;
valuethree = n;/*To get the hundreds place digit*/
sum = valuethree + valuetwo;/*adding the hundreds place and
tens place*/
}
/*Checking if the ones place digit is equal to the sum and then print
the values in a string format*/
if (sum == valueone) {
Numbers = Numbers + n + " ";
System.out.println(Numbers);
}
}
}
}
I got my result :
1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000001
100000000011
1000000000111
10000000001111
100000000011111
1000000000111111
10000000001111111
100000000011111111
1000000000111111111
Process finished with exit code 0
The result is not showing the actual result like it should be which should show values like: 123, 246 (Please refer to the problem statement above.)
Please let me know what seems to be the issue with the code and how to tweak it.
Don't know what you're trying to do with that while loop, or why you are building up a space-separated string of numbers.
Your code should be something like:
for (int n = 1; n <= 999; n++) {
int digit1 = // for you to write code here
int digit2 = // for you to write code here
int digit3 = // for you to write code here
if (digit1 + digit2 == digit3) {
// print n here
}
}
So basically your question is how to calculate the numbers, right?
My first hint for you would be how to get the first, second and third value from a 2 or 3 digit number.
For example for 3 digits you can do int hundretDigit = (n - (n % 100)) % 100. Of course this is really inefficient. But just get code working before optimizing it ;)
Just think about a way to get the "ten-digit" (2nd number). Then you add them and if they equal the third one you write System.out.println(<number>);
EDIT:
For 2 digit numbers I will give you the code:
if(i >= 10 && i <= 99) {
int leftDigit = (i - (i % 10)) / 10;
if(leftDigit == (i % 10)) {
//Left digit equals right digit (for example 33 => 3 = 3
System.out.println(i);
}
}
Try again and edit your source code. If you have more questions I will edit my (this) answer to give you a little bit more help if you need!

How to get nearest highest multiple of 9 in java

I need something that can calculate the nearest highest multiple of 9. So for example, if I input 1 into this function it will return 9, if I input 10 into this function it will return 18 and so on.
I've tried this 9*(Math.round(number/9)) and 9*(Math.ceil(Math.abs(number/9))) but they return the nearest multiple of 9, so if you input 10 into this function it will return 9, for my purposes it will need to return 18. (There's probably a better way to say this other then "nearest highest")
If anyone can help me that will be great!
You can use this formula.
number + (9 - (number % 9))
And for the exceptional case when the number is a multiple of 9, use a condition:
int result = number % 9 == 0 ? number : number + (9 - (number % 9));
Just add one (max) 9 times and check if it is a multiple of 9 like so:
int x = 9;
int result = 0;
for (int i = x; i < 9; i++)
{
if (i % 9 == 0)
{
result = i;
break;
}
}
// result will contains the 'nearest' 'highest' or it self multiple of 9
You can try defining a multiplier whose value depends on whether number is multiple of 9 or not. Check below code:
int number = 10;
Double ceilValue = Math.ceil(number/9);
double multiplier = 0.0;
if (number % 9 == 0) {
multiplier = ceilValue;
} else {
multiplier = ceilValue + 1;
}
Double result = 9 * multiplier;
System.out.println(result);
Output:18.0

How to get even/odd random number divisible by first random number

I have following code:
quesPart1 = ran.nextInt((numbersBetween - 2) + 1) + 2;
quesPart2 = ran.nextInt((numbersBetween - 2) + 1) + 2;
if(quesPart2 > quesPart1)
{
int placeHolder = quesPart1;
quesPart1 = quesPart2;
quesPart2 = placeHolder;
}
//if first part is even
if(quesPart1 % 2 == 0)
{
if(quesPart2 % 2 != 0)
{
--quesPart2;
}
}
else
{
if(quesPart2 % 2 == 0)
{
++quesPart2;
}
}
Above code make sure that if quesPart1 is greater than quesPart2 and both are even or both are odd numbers. Now i want to get only random numbers which are also divisible by one another. Like if i divide quesPart1 by quesPart2 i get integer not decimal number. Any ideas how i can do that without adding too much complexity to above code.
You can do something like:
int div = quesPart1 / quesPart2;
quesPart1 = div * quesPart2;
add this code at the bottom of your code.
Like if i divide quesPart1 by quesPart2 i get integer not decimal number.
Keep it simple: generate random numbers and take their product. Example:
quesPart2 = ran.nextInt(UPPER_BOUND);
int temp = ran.nextInt(UPPER_BOUND);
questPart1 = temp * quesPart2;
Specifying the range, as in the original question, is left an an exercise to the reader. (What, you didn't think I was going to do all the thinking for you, did you? ;-)
Look into the modulus operator, a % b. It returns the left over amount when a is divided by b. When b cleanly divides into a, such that there is no decimal part, a % b will be zero.
In order to generate a number that is divisible by another, given two random numbers, a and b, simply multiply a by b. This will give you c, a number that is a multiple of both a and b, and therefore dividable by both cleanly without remainder.
I have come up with this simple function and a do while loop that is easy to implement.
// This is a simple function to set the min and max integers you want
const getRandomIntInclusive = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//Define some variables variables
let firstNo = 0
let secondNo = 0
let isDivisible = 0;
//generate random ints until first number is divisible to second number
do {
//get random int between 1-9 for the first and second integer
firstNo = getRandomIntInclusive(1, 9)
secondNo = getRandomIntInclusive(1, 9)
isDivisible = firstNo % secondNo; //Check if it's fully divisible
}
while (isDivisible != 0) //Run until it is fully divisible
To generate Random numbers in java you can use ran.nextInt() or please refer to this link to see how to generate random numbers.
store those 2 random numbers (as num1 and num2).
To verify whether the solution after dividing num1 and num2 is integer or not, use this method:
sol = num1 / num2
if (sol == (int)sol)
{
... //true if the solution is an integer
}

Java recursion and integer double digit

I'm trying to take an integer as a parameter and then use recursion to double each digit in the integer.
For example doubleDigit(3487) would return 33448877.
I'm stuck because I can't figure out how I would read each number in the digit I guess.
To do this using recursion, use the modulus operator (%), dividing by 10 each time and accumulating your resulting string backwards, until you reach the base case (0), where there's nothing left to divide by. In the base case, you just return an empty string.
String doubleDigit(Integer digit) {
if (digit == 0) {
return "";
} else {
Integer thisDigit = digit % 10;
Integer remainingDigits = (digit - thisDigit) / 10;
return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString();
}
}
If you're looking for a solution which returns an long instead of a String, you can use the following solution below (very similar to Chris', with the assumption of 0 as the base case):
long doubleDigit(long amt) {
if (amt == 0) return 0;
return doubleDigit(amt / 10) * 100 + (amt % 10) * 10 + amt % 10;
}
The function is of course limited by the maximum size of a long in Java.
I did the same question when doing Building Java Programs. Here is my solution which works for negative and positive numbers (and returns 0 for 0).
public static int doubleDigits(int n) {
if (n == 0) {
return 0;
} else {
int lastDigit = n % 10;
return 100 * doubleDigits(n / 10) + 10 * lastDigit + lastDigit;
}
There's no need to use recursion here.
I'm no longer a java guy, but an approximation of the algorithm I might use is this (works in C#, should translate directly to java):
int number = 3487;
int output = 0;
int shift = 1;
while (number > 0) {
int digit = number % 10; // get the least-significant digit
output += ((digit*10) + digit) * shift; // double it, shift it, add it to output
number /= 10; // move to the next digit
shift *= 100; // increase the amount we shift by two digits
}
This solution should work, but now that I've gone to the trouble of writing it, I realise that it is probably clearer to just convert the number to a string and manipulate that. Of course, that will be slower, but you almost certainly don't care about such a small speed difference :)
Edit:
Ok, so you have to use recursion. You already accepted a perfectly fine answer, but here's mine :)
private static long DoubleDigit(long input) {
if (input == 0) return 0; // don't recurse forever!
long digit = input % 10; // extract right-most digit
long doubled = (digit * 10) + digit; // "double" it
long remaining = input / 10; // extract the other digits
return doubled + 100*DoubleDigit(remaining); // recurse to get the result
}
Note I switched to long so it works with a few more digits.
You could get the String.valueOf(doubleDigit) representation of the given integer, then work with Commons StringUtils (easiest, in my opinion) to manipulate the String.
If you need to return another numeric value at that point (as opposed to the newly created/manipulated string) you can just do Integer.valueOf(yourString) or something like that.

Retrieving the first digit of a number [duplicate]

This question already has answers here:
Return first digit of an integer
(25 answers)
Closed 5 years ago.
I am just learning Java and am trying to get my program to retrieve the first digit of a number - for example 543 should return 5, etc. I thought to convert to a string, but I am not sure how I can convert it back? Thanks for any help.
int number = 534;
String numberString = Integer.toString(number);
char firstLetterChar = numberString.charAt(0);
int firstDigit = ????
Almost certainly more efficient than using Strings:
int firstDigit(int x) {
while (x > 9) {
x /= 10;
}
return x;
}
(Works only for nonnegative integers.)
int number = 534;
int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
firstDigit = number/((int)(pow(10,(int)log(number))));
This should get your first digit using math instead of strings.
In your example log(543) = 2.73 which casted to an int is 2.
pow(10, 2) = 100
543/100 = 5.43 but since it's an int it gets truncated to 5
int firstDigit = Integer.parseInt(Character.toString(firstLetterChar));
int number = 534;
String numberString = "" + number;
char firstLetterchar = numberString.charAt(0);
int firstDigit = Integer.parseInt("" + firstLetterChar);
Integer.parseInt will take a string and return a int.
This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.
private static int getMostSignificantDigit(double value) {
value = Math.abs(value);
if (value == 0) return 0;
while (value < 1) value *= 10;
char firstChar = String.valueOf(value).charAt(0);
return Integer.parseInt(firstChar + "");
}
To get the first digit, this sticks with String manipulation as it is far easier to read.
int number = 534;
int firstDigit = number/100;
( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .
but if you want to get the last number , you can use (%) operator
int lastDigit = number%10;
which gives us the reminder of the division , so 534%10 , will yield the number 4 .
This way might makes more sense if you don't want to use str methods
int first = 1;
for (int i = 10; i < number; i *= 10) {
first = number / i;
}

Categories