Removing numbers from integer - java

I'd like to know how to remove numbers from an integer. For example, if I have the number 23875326, I want to remove the odd numbers, and get the result of 2826.
I've been trying to break each number to check if it's even or odd using a while loop, but I don't know how to merge the numbers into one integer. One important thing is, I'd like to do it without using strings, as it doesn't teach me anything new that way.

I actually think that dealing with a string of numbers is preferable, not only from a code readability point of view, but also possibly from a performance view. That being said, if we absolutely cannot use strings here, then it is still possible to work directly with the integer input.
We can examine each tens digit of the input number using num % 10. Should that digit be even, we can add it to the output number, otherwise do not add it. Note that at each iteration we need to scale the digit by 10 to the correct exponent.
Here is a working code snippet:
int length = (int) (Math.log10(num) + 1); // finds the number of digits
int output = 0;
int counter = 0;
for (int i=0; i < length; ++i) {
if ((num % 10) % 2 == 0) {
output += (num % 10) * Math.pow(10, counter);
++counter;
}
num = num / 10;
}
System.out.println(output);
2826
Demo

I used #Tim Biegeleisen code and changed it a bit, removed some code and changed the for loop to while loop:
int output = 0;
int counter = 0;
System.out.println("Enter a number");
int num = s.nextInt();
while (num != 0) {
if ((num % 10) % 2 == 0) {
output += (num % 10) * Math.pow(10, counter);
++counter;
}
num = num / 10;
}
System.out.println(output);`

Related

The loop has no output?

The code below has no output when I run it, I think somehow it is infinite loop? How to fix it?
Write a method named getEvenDigitSum with one parameter of type int called number.
The method should return the sum of the even digits within the number.
If the number is negative, the method should return -1 to indicate an invalid value.
EXAMPLE INPUT/OUTPUT:
getEvenDigitSum(123456789); → should return 20 since 2 + 4 + 6 + 8 = 20
getEvenDigitSum(252); → should return 4 since 2 + 2 = 4
getEvenDigitSum(-22); → should return -1 since the number is negative
public class getEvenDigitSum {
public static int getEvenDigitSum(int number) {
int sum = 0;
int lastDigit=0;
if (number < 0) {
return -1;
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
return sum;
}
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
OK, and what happens if the number isn't even? You didn't make an else/else if statement after; if your number is odd, it stays the same, the loop is infinite, and hence your code does nothing.
Your condition only handles even digits, but think about what happens when you get a number that contains odd digit, like 1221 for example.
Try adding the missing else statement:
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
else {
// Deal with odd digit, leaving for you to implement
{
}
General tip: The best way to find errors in your code is to write tests and debug your code.
These are two skills every developer should poses and practice regularly

Sum even index places in Java

I tried to write a method (for kicks) that would sum up the digits at even places using Java recursion.
For example, the number 23495 would return 3+9 = 12.
I am unsuccessful and would appreciate hints or what I'm doing wrong.
int sumEven = 0;
int sumOdd = 0;
int i = 1;
if (n == 0)
return sumEven;
if (n != 0) {
if (i % 2 == 0)
{
i++;
sumEven += n % 10;
}
else
{
i++;
sumOdd += n % 10;
}
}
return sumEven + getEven (n/=10);
The problem is you're trying to do too much - take a look at my comment on the Q
A recursive method needs an input that contains everything it needs to work with, a return value, and an execution path where it calls itself until something happens that means it doesn't need to call itself any more - without this bit it will recourse until it overflows the stack
int sumEveryOtherDigit(int input){
if(input >= 100)
return input%10 + sumEveryOtherDigit(input/100);
else
return input%10;
}
This takes the input , and if there is any point to running again (if the input is at least 100) takes the rightmost digit plus running itself again with a smaller number
Eventually the number gets so small that there isn't any point running itself again so it just returns without running itself again and that is how the recursion stops
Now from your comment on another answer it seems you want to determine even and odd as working from the left so we need to either start with the number (1630) or the number divided by ten (23495 -> 2349) - basically to start the recursion going we always want to pass in a number with an even number of digits
int num = 23495;
int numOfDigits = (int)Math.log10(num)+ 1;
if(numOfDigits%2==0)
result = sumEveryOtherDigit(num);
else
result = sumEveryOtherDigit(num/10);
You should iterate over the digits of the input number, and then sum the remainder mod 10 only for even position digits:
int input = 23495;
input /= 10;
int sum = 0;
while (input > 0) {
sum += input % 10; // add last even digit
input /= 100; // advance by two digits, to the next even digit
}
System.out.println("sum of even digits of input is: " + sum);
This prints:
sum of even digits of input is: 12

Reorder numbers in a int number to get minimum value

How can I reorder numbers in a int number to get minimum value.
Ex:
I input a number: $71440 and I want my output is: $1447 (this is minimum value after reordering). I think I will spits the numbers in my input number first like this , after that I will reorder them. That is good algorithm?
Yes it is good if you
split by digit
sort digits
make number out of those digits
What you need is essentially a sorting of the digits of the number. So yes, your proposed method will work and it seems as a reasonable practice.
I think this does roughly what you want it to do. Assumes that the input is positive, I'm sure you can figure out how to modify it to work with negative numbers if you need that.
public static int leastValue(int input) {
String s = Integer.toString(input);
char[] c = s.toCharArray();
Arrays.sort(c);
s = new String(c);
return Integer.parseInt(s);
}
The basic idea is:
Turn value into a string
Put each character into an array
Sort the array of characters, in most character sets this will order the numbers from smallest to largest.
Turn it into a string again
Parse it into an int
For readability I think Diasiares answer is better. However a different approach would be something like this. It sorts a long with a "merge sort like" algorithm. To understand how it works please view the gif file from wikipedia
public static long sort(long num) {
long res;
if (num > 9) {
//split num into two parts(n1, n2)
int numberOfDigits = (int) Math.log10(num) + 1;
long n1 = num / (long) Math.pow(10, numberOfDigits / 2);
long n2 = num % (long) Math.pow(10, numberOfDigits / 2);
//sort each part
long s1 = sort(n1);
long s2 = sort(n2);
//merge them into one number
res = merge(s1, s2);
} else {
res = num;
}
return res;
}
/**
* merges two sorted long into on long e.g 149 and 345 will give 134459
*/
public static long merge(long num1, long num2) {
return (num1 == 0 || num2 == 0)
? num1 + num2
: num1 % 10 < num2 % 10
? num2 % 10 + merge(num1, num2 / 10) * 10
: num1 % 10 + merge(num1 / 10, num2) * 10;
}

How to print an int with comma divisors using a recursive method (no strings)?

In my computer science class, we were assigned a lab on recursion in which we have to print out a number with commas separating groups of 3 digits.
Here is the text directly from the assignment (the method has to be recursive):
Write a method called printWithCommas that takes a single nonnegative
primitive int argument and displays it with commas inserted properly.
No use of String.
For example printWithCommas(12045670); Displays 12,045,670
printWithCommas(1); Displays 1
I am really stumped on this. Here is my code so far:
public static void printWithCommas(int num) {
//Find length
if (num < 0) return;
int length = 1;
if (num != 0) {
length = (int)(Math.log10(num)+1);
}
//Print out leading digits
int numOfDigits = 1;
if (length % 3 == 0) {
numOfDigits = 3;
}
else if ((length+1) % 3 == 0) {
numOfDigits = 2;
}
System.out.print(num / power(10,length-numOfDigits));
//Print out comma
if (length > 3) {
System.out.print(',');
}
printWithCommas(num % power(10,length-numOfDigits));
}
It gets a stack overflow (which I can fix later), but it fails to print out some of the zeros, specifically the ones that are supposed to be after each comma.
I feel like I am taking this on with a completely wrong approach, but can't think of a good one. Any help would be appreciated.
Thanks in advance!
Note: power is a function I made that calculates power. First argument is the base, second is the exponent.
Here is the code I came up with, for anyone else that might be stuck on this:
public static void printWithCommas(int num) {
if (num > 999) {
printWithCommas(num/1000);
System.out.print(',');
if (num % 1000 < 100) System.out.print('0');
if (num % 1000 < 10) System.out.print('0');
System.out.print(num%1000);
}
else {
System.out.print(num);
}
}

Reverse of a number taking care of boundary conditions

I'm trying to write a simple method in Java that return the reverse of a number (in the mathematical way, not string-wise). I want to take care of boundary conditions since a number whose reverse is out of int range would give me a wrong answer. Even to throw exceptions, I'm not getting clearcut logic. I've tries this code.
private static int reverseNumber(int number) {
int remainder = 0, sum = 0; // One could use comma separated declaration for primitives and
// immutable objects, but not for Classes or mutable objects because
// then, they will allrefer to the same element.
boolean isNegative = number < 0 ? true : false;
if (isNegative)
number = Math.abs(number); // doesn't work for Int.MIN_VALUE
// http://stackoverflow.com/questions/5444611/math-abs-returns-wrong-value-for-integer-min-value
System.out.println(number);
while (number > 0) {
remainder = number % 10;
sum = sum * 10 + remainder;
/* Never works, because int won't throw error for outside int limit, it just wraps around */
if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
throw new RuntimeException("Over or under the limit");
}
/* end */
/* This doesn't work always either.
* For eg. let's take a hypothetical 5 bit machine.
* If we want to reverse 19, 91 will be the sum and it is (in a 5 bit machine), 27, valid again!
*/
if (sum < 0) {
throw new RuntimeException("Over or under the limit");
}
number /= 10;
}
return isNegative ? -sum : sum;
}
Your approach of dividing by 10, transfering the reminder to the current result * 10 is the way to go.
The only thing you are doing wrong is the check for the "boundary violation", because
sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE
can ofc. NEVER be true - Otherwhise MIN and MAX wouldn't have any meaning.
So, think mathematical :-)
sum = sum * 10 + remainder;
should not exceed Integer.MAX_VALUE, i.e.
(!)
Integer.MAX_VALUE >= sum * 10 + remainder;
or transformed:
(!)
(Integer.MAX_VALUE - remainder) / 10 >= sum
So, you can use the following check BEFORE multiplying by 10 and adding the remainder:
while (number > 0) {
remainder = number % 10;
if (!(sum <= ((Integer.MAX_VALUE -remainder) / 10))) {
//next *10 + remainder will exceed the boundaries of Integer.
throw new RuntimeException("Over or under the limit");
}
sum = sum * 10 + remainder;
number /= 10;
}
simplified (DeMorgan) the condition would be
if (sum > ((Integer.MAX_VALUE -remainder) / 10))
which makes perfect sence - because its exactly the reversed calculation of what your next step will be - and if sum is already GREATER than this calculation - you will exceed Integer.MAX_VALUE with the next step.
Untested, but that should pretty much solve it.

Categories

Resources