Java- Builiding a recursion that replace even digits with zero - java

Hello i need to build a recursion that replace the even digits with zero:
for exmaple - the number 1254 will be 1050
the number 332- will be 330
and the number 24 - will be 0
i started working on it but got pretty clueless after a while
public static int replaceEvenDigitsWithZero(int number){
if(number<1)
return number;
if(number%2==0 && number%10!=0){
int temp=number%10;
return(number/10+replaceEvenDigitsWithZero(number-temp));
}
return(replaceEvenDigitsWithZero(number/10));
}
public static void main(String[] args) {
int num1 = 1254;
System.out.println(num1 + " --> " + replaceEvenDigitsWithZero(num1));
int num2 = 332;
System.out.println(num2 + " --> " + replaceEvenDigitsWithZero(num2));
int num3 = 24;
System.out.println(num3 + " --> " + replaceEvenDigitsWithZero(num3));
int num4 = 13;
System.out.println(num4 + " --> " + replaceEvenDigitsWithZero(num4));
}
}

Since your method only looks at the last digit, it should always call itself with input / 10 when input >= 10.
You then take the value returned by the recursion, multiply it by 10 and add the last digit back, if odd.
public static int replaceEvenDigitsWithZero(int number) {
int result = 0;
if (number >= 10)
result = replaceEvenDigitsWithZero(number / 10) * 10;
if (number % 2 != 0)
result += number % 10;
return result;
}

In case you need a 1-liner, here it goes: ;)
public static int replaceEvenDigitsWithZero(int number) {
return (number%2 == 0 ? 0 : number % 10) + (number<10 ? 0 : 10 * replaceEvenDigitsWithZero(number / 10));
}

Well ... designing a recursive algorithm has always the same steps:
Identify the base case, that is the scenario that will terminate the recursive calls.
Reduce the problem to being smaller (towards the base case).
For this requirement the problem can easily be made smaller by dividing by 10. That also easily leads to the base case: A single digit is the base case. So a quick implementation can be:
public static int replaceEvenDigitsWithZero(int number) {
// I added handling of negative numbers ...
if (number < 0) {
return -replaceEvenDigitsWithZero(-number);
}
// base case
if (number < 10) {
return replaceOneDigit(number);
}
// recursion
int lastDigit = number % 10;
int remainder = number / 10;
return replaceEvenDigitsWithZero(remainder) * 10 + replaceOneDigit(lastDigit);
}
public static int replaceOneDigit(int digit) {
return (digit % 2 == 0) ? 0 : digit;
}
I added a helper method for converting even digits to zero.
The output now is:
1254 --> 1050
332 --> 330
24 --> 0
13 --> 13

You need to take track of the current position in your number.
In your current function, you will return only the first digit of your number (because you divide it by 10 everytime the recursion is called).
public static int replaceEvenDigitsWithZero(int number, int position){
// cancel condition:
if(number < 10 * position) {
return number;
}
// edit number:
if (position > 0) {
int currentNumber = number / (10 * position);
} else {
currentNumber = number;
}
if(currentNumber%2==0){ //even?
int multiplyValue = currentNumber % 10; // get rest of division by 10 (== digit in current position)
number = number - (multiplyValue * (10 * position)); // set current position to zero
}
// recursive call:
return replaceEvenDigitsWithZero(number,position+1);
}
Didn't test my code, but I hope you get an idea of how to do it.
Use replaceEvenDigitsWithZero(num1,0) to start.

1 convert to String
2 F(string): take the first number: replace 2,4,6,8 characters by 0
3 concatenate to F(the remaining string)
4 convert to int

Related

How do you add digits to the front of a number?

How would you add digits to the beginning of a number (left hand side) without using a string?
I know that if you try this:
(Some psuedo code)
Let's say I try to make number 534
int current = 5;
int num = 0;
num = (num*10) +current;
then
int current = 3;
int num = 5
num = (num*10) + current;
would make: 53
then
int current = 4;
int num = 53;
num = (num*10) + current;
would make 534
It would keep adding numbers to the right hand side of the number.
However, I am a bit confused on how you would do the opposite. How would you add numbers on the left, so instead of 534 it makes 435?
int num = 123;
int digits = 456;
int powerOfTen = (int) Math.pow(10, (int) (Math.log10(digits) + 1));
int finalNum = digits * powerOfTen + num;
System.out.println(finalNum); // Output: 456123
The number of digits in digits is calculated using Math.log10 and Math.pow, and then used to determine the appropriate power of 10 to multiply digits by. The result is then added to num to obtain the final number with the added digits.
Multiply the digit to add by increasing powers of 10 before summing with the current number.
int num = 0, pow = 1;
num += 5 * pow;
pow *= 10;
num += 3 * pow;
pow *= 10;
num += 4 * pow; // num = 435 at this point
pow *= 10;
// ...
An example without the use of libraries could be this:
First, get the number of digits. Then calculate the number you have to add to your initial number. The sum of these two numbers is the result you're after.
private int addNumberInFrontOf(int initialNumber, int initialNumberToAdd){
int numberOfDigits = getDigits(initialNumber);
int getActualNumberToAdd = getNumberToAdd(initialNumberToAdd, numberOfDigits);
return initialNumber + getActualNumberToAdd;
}
To calculate the number of digits, you can count the number of times you can divide the initial number by 10. Notice you need to use a do-while loop because otherwise the loop wouldn't be triggered if your initial number was 0.
private int getDigits(int number) {
int count = 0;
do {
number = number / 10;
count += 1;
} while (number != 0);
return count;
}
Calculate the number you need to add to your initial number by multiplying the initial number to add with the magnitude. The magnitude simply is 1 multiplied with 10 for every digit in the initial number.
private int getNumberToAdd(int number, int numberOfDigits) {
int magnitude = 1;
for (int i = 0; i < numberOfDigits; i++) {
magnitude *= 10;
}
return number * magnitude;
}
For example, addNumberInFrontOf(456, 123) would result in 123456. Of course, this method won't work when you use positive and negative numbers combined.
You can use String for example.
public static int addLeft(int cur, int num) {
return num == 0 ? cur : Integer.parseInt(cur + String.valueOf(num));
}
In case you want to avoid working with String, you can use recursion instead.
public static int addLeft(int cur, int num) {
return num == 0 ? cur : addLeft(cur, num / 10) * 10 + num % 10;
}
You can use some math, in python
import math
def addLeft(digit, num):
return digit * 10 ** int(math.log10(num) + 1) + num
Note that this might fail for very large numbers on account of precision issues
>>> addLeft(2, 100)
2100
>>> addLeft(3, 99)
399
>>> addLeft(6, 99999999999999)
699999999999999
>>> addLeft(5, 999999999999999)
50999999999999999 (oops)

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

Java - How to check if a 13 digit isbn number is valid

I need to write a program that allows the user to enter a 13-digit ISBN as a single integer.
The program should then determine and show whether the number is valid according to the formula above. It also needs to print an error message if the user tries to enter a number longer than 13 digits.
Below is the code I am working on.
I'm new to java and I don't understand where it went wrong. I also don't seem to figure out how to get the length of a long variable.
import java.util.Scanner;
public class ISBNChecker{
public static void main(String [] args){
long isbnNumber;
long isbnTotal;
long x;
Scanner scnr = new Scanner(System.in);
isbnNumber = scnr.nextLong();
while (isbnNumber > 0) {
x = isbnNumber % 10;
isbnTotal = total + x;
isbnNumber = isbnNumber / 10;
x = isbnNumber % 10;
isbnTotal = total + (3 * x);
isbnNumber = isbnNumber / 10;
}
if (isbnTotal % 10 = 0) {
System.out.println("Number is valid!");
}
else {
System.out.println("Number is invalid.");
}
}
}
Fix your (own) current code
In your original code, you have a couple of tiny errors:
isbnTotal = total + x;
total is not declared anywhere, and isbnTotal is not initialized.
if (isbnTotal % 10 = 0) {
You need to compare with double =, a single one is for assignation, double == is for comparison.
Separate your code into modules to improve it
... determine and show whether the number is valid according to the formula above.
I think that you forgot to write the formula, but according to Wikipedia, is this one:
So, you need to check if the sum of all digits multiplied by their weight (alternating 1 and 3) is a multiple of 10.
So, first of all we need to get the sum of all digits and multiply each digit by 1 or 3 alternating (backwards as we're gonna be using the modulo operator).
So, we need something like this:
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
Let me explain what the above code does, is make use of the ternary operator (CTRL-F on the page to read about it), to determine if we need to multiply by 1 or 3, in the formula it starts with 1, so the easiest way to do it is by checking if the current index is even or odd, if even, multiply by 1, otherwise multiply by 3, and adds that number to the sum.
Then it divides the current number by 10.
Then all we have to do is check if the sum of all digits multiplied by their respective weights is a multiple of 10.
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
And just before that, if the given number doesn't have 13 digits, we say that it isn't.
So, in the end our program should be something like:
public class ISBNChecker {
public static void main(String[] args) {
String isbnNumber = "978030640615";
if (isbnNumber.length() != 13) {
System.out.println("ISBN Number is invalid");
return;
}
if (isAValidISBN(Long.parseLong(isbnNumber))) {
System.out.println(isbnNumber + " is a valid ISBN");
} else {
System.out.println(isbnNumber + " is not a valid ISBN");
}
}
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
}
And if we take the Wikipedia value, we get this output:
9780306406157 is a valid ISBN
I don't understand your question clearly, but I suppose what you want to do is validate if the number provided by the user has 13 digits or not, you could do this:
public static void main(String[] args) {
String userNumber;
Scanner scnr = new Scanner(System.in);
System.out.println("Enter ISBN number, 13 digit");
userNumber = scnr.nextLine();
/*regular expression to verify that it contains only 13 digits*/
if(userNumber.matches("^[0-9]{13}$")) {
System.out.println("Number is valid");
} else {
System.out.println("Number is invalid");
}
}
First of all, what do you mean with:
according to the formula above.
What formula do you mean? And Second, to get the length of an long or integer just do:
int length = ("" + isbnNumber).length()
And btw, when you are doing an if statement do "==" instead of "=".
if (isbnTotal % 10 = 0) {
…should be:
if (isbnTotal % 10 == 0) {
Or better, reverse so compiler would have caught your typo.
if (0 == isbnTotal % 10) {

Write a program to round a number to the next multiple of 10 given the following conditions?

Write a program to Round a number to the next multiple of 10 if its ones digit is 5 or more, otherwise round it the previous multiple of 10.So, 25 and 26 round to 30 where as 23 and 24 round to 20. 20 also rounds to 20. You have been given 4 ints as input. Round each of the input values and return their sum.
MyApproach
I created 2 functions in the first function I counted the sum of all 4 numbers.
In the second function I checked the UnitDigtit if>=5 &&<=9 Then proceed with set of statements given in the question.
else
I checked if Its a one digit or two or any digit number.If One digit I returned num=0 else I proceded with the sets of statements.
Sample Input #1
sumRounded(11,15,23,30)
Sample Output #1
80 (11 rounds to 10, 15 to 20, 23 to 20 and 30 to 30)
Sample Input #2
sumRounded(1,3,7,9)
Sample Output #2
20
public int sumRounded(int num1, int num2, int num3, int num4)
{
int a=checkRound(num1);
int b=checkRound(num2);
int c=checkRound(num3);
int d=checkRound(num4);
return a+b+c+d;
}
public int checkRound(int num)
{
int a=num%10;
if((a>=5) &&(a<=9))
{
if(a==5)
{
num=num+5;
}
else if(a==6)
{
num=num+6;
}
else if(a==7)
{
num=num+7;
}
else if(a==8)
{
num=num+8;
}
else if(a==9)
{
num=num+9;
}
return num;
}
else
{
if((num/10)!=0)
{
if(a==1)
{
num=num-1;
}
else if(a==2)
{
num=num-2;
}
else if(a==3)
{
num=num-3;
}
else if(a==4)
{
num=num-4;
}
return num;
}
else
{
return num=0;
}
}
}
Results:
Parameters Actual Output Expected Output
'289' '3' '25' '308' 644 630
Rounding
If the remainder is less than 5, subtract it from num. Otherwise, add ten minus the remainder to the num. Something like,
static int checkRound(int num) {
int rem = num % 10;
return rem < 5 ? num - rem : num + (10 - rem);
}
or use Math.round(float) like
static int checkRound(int num) {
return Math.round((float) num / 10) * 10;
}
Varargs
You could also implement sumRounded as a varargs method with a for-each loop
static int sumRounded(int... nums) {
int sum = 0;
for (int num : nums) {
sum += checkRound(num);
}
return sum;
}
Testing
Then you could test it like,
public static void main(String[] args) {
System.out.println(sumRounded(11, 15, 23, 30)); // == 80
System.out.println(sumRounded(1, 3, 7, 9)); // == 20
}
Simply use the reminder check inside checkRounded method
int number = 23;
int output=0;
if(number%10<5){
output=(number/10)*10;
}
else{
output=((number/10)+1)*10;
}
System.out.println(output);
You simply put following code in you chexkRound method
int a = num % 10;
if ((a >= 5) && (a <= 9)) {
num = 10 * (num / 10 + 1);
} else {
num = 10 * (num / 10);
}
return num;
If you want to fix you way do the following but Exbury's answer is a shorter way of doing it.
If you are rounding up you should add the 10 minus the number, not the number itself. So for example, 26 rounded up should be 26+(10-6) = 26+(4) = 30
Well the following code perfectly suits your need
//code starts
public static void main(String[] args) {
System.out.println("The answer is: " + getSum(2,5,19));
}
public static int getSum(int... nums) {
int sum = 0;
for (int n : nums) {
int lastDigit = n % 10;
if (lastDigit >= 5) {
sum = sum + n + (10 - (lastDigit));
} else {
sum = sum + 10 * (n / 10);
}
}
return sum;
}
//code ends

Credit Card Number validity with Luhn's Algorithm (Java)

I'm working on a school assignment that checks whether a credit card number that is entered is valid or not, using Luhn's Algorithm.
In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine whether a card number is entered correctly or whether a credit card is scanned correctly by a scanner. Credit card numbers are generated following this validity check, commonly known as the Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number 4388 5760 1840 2626):
Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.
Now add all single-digit numbers from Step 1: 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37
Add all digits in the odd places from right to left in the card number: 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
Sum the results from Step 2 and Step 3: 37 + 38 = 75
If the result from Step 4 is divisible by 10 the card number is valid; otherwise, it is invalid. For example, the number 4388 5760 1840 2626 is invalid, but the number 4388 5760 1841 0707 is valid.
I need to write this program using the methods in the code I have written:
public class CreditCardValidation {
public static void main(String[] args, long input) {
Scanner numberinput = new Scanner(System.in);
System.out.println("Enter a credit card number as a long integer: ");
long cardnumber = numberinput.nextLong();
if (isValid(input) == true) {
System.out.println(numberinput + " is valid.");
} else {
System.out.println(numberinput + " is invalid.");
}
}
public static boolean isValid(long number){
int total = sumOfDoubleEvenPlace + sumOfOddPlace;
return (total % 10 == 0) && (prefixMatched(number, 1) == true) &&
(getSize(number)>=13) && (getSize(number)<=16);
}
public static int sumOfDoubleEvenPlace(long number) {
int doubledevensum = 0;
long place = 0;
while (number > 0) {
place = number % 100;
doubledevensum += getDigit((int) (place / 10) * 2);
number = number / 100;
}
return doubledevensum;
}
public static int sumOfOddPlace(long number) {
int oddsum = 0;
while (number <= 9) {
oddsum += (int)(number % 10);
number = number % 100;
}
return oddsum;
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int)(number / 10);
return firstDigit + secondDigit;
}
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 3) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int)getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
}
I just started learning how to program two months ago so I am fairly new to this. The program doesn't compile and I don't know why and what I have to do to fix this. I know there are similar topics already posted regarding this and I have been using this post to help guide me a bit. Can someone help point a student in the right direction and let me know what I'm doing wrong?
Your program isn't compiling because this line:
int total = sumOfDoubleEvenPlace + sumOfOddPlace;
since sumOfDoubleEvenPlace and sumOfOddPlace are functions, you must use them as such:
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
In the function isValid you are trying to add two variables which do not exist. However you have defined them as functions and to use them as functions you must call them as functions using
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);

Categories

Resources