I need to write a method that receives a number, and for any even digits in it, replaces them with the 0 digit.
I think I'm going in the right direction, but when I run it with the debugger, I seen the even numbers don't return to 0 in even digit.
This is what I have so far.
I know my English is poor, so here's an example example.
For the number 12345, the method should return 10305
For the number 332, the method should return 330.
I hope that's understandable. Here's my code:
public class Assignment1 {
public static void main(String[] args) {
System.out.println(Even(12345));
}
private static int Even(int n) {
if (n == 0 ) {
return 0 ;
}
if (n % 2 == 0) { // if its even
n= n/10*10; // we cut the right digit from even number to 0
return (n/10 %10 ) + Even(n/10)*0;
}
return Even(n/10)*10 +n;
}
}
Your base case is only checking if the number is zero. Check this solution, and let me know if you have doubts!
public int evenToZero(int number){
//Base case: Only one digit
if(number % 10 == number){
if(number % 2 == 0){
return 0;
}
else{
return number
}
}
else{ //Recursive case: Number of two or more digits
//Get last digit
int lastDigit = number % 10;
//Check if it is even, and change it to zero
if(lastDigit % 2 == 0){
lastDigit = 0;
}
//Recursive call
return evenToZero(number/10)*10 + lastDigit
}
}
Below is a recursive method that will do what you need. Using strings will be easier because it allows you to 'add' the number digit by digit. That way, using 332 as example, 3+3+0 becomes 330, and not 6.
Every run through, it cuts of the digit furthest right so 332 becomes 33, then 3, and then 0.
public static void main(String[] args) {
System.out.println(Even(12345));
}
private static String Even(int n) {
if(n==0)
return "";
else if(n%2==0){
return Even(n/10) + "0";
}
else{
String s = Integer.toString(n%10);
return Even(n/10) + s;
}
}
Related
I had a test exam in java, that almost no one have succeeded in this question and I can't figure out the solution.
The question was like this:
Find the sum of an integer last and first number. For example 1234-->5, 137-->8, 4-->8. You are only allowed to use recursion and no helper function"
I tried various things. Here is my last attempt:
public static int sumOfFirstandLastdigits(int number)
{
int lastdigit=sumOfFirstandLastdigits(number/10);
if(number/10==0)
{
return number%10;
}
return lastdigit+sumOfFirstandLastdigits(number%10);
}
Assuming the input is supposed to be non-negative:
//If n < 0, return first digit of -n
//Otherwise, return sum of first and last digits of n
int sumLastAndFirstDigit(int n) {
if (n < -9)
return sumLastAndFirstDigit(-(-n/10));
if (n <= 0)
return -n;
if (n < 10)
return n+n;
return n%10 + sumLastAndFirstDigit(-(n/10));
}
You can do this by overloading the method and passing the last digit as a second parameter to keep track of it through the recursion without changing the value (AKA Default Parameter):
public static void main(String[] args) {
System.out.println(sumDigits(3891901));
System.out.println(sumDigits(1234));
System.out.println(sumDigits(5678));
}
private static int sumDigits(int i) {
return sumDigits(i, i % 10);
}
private static int sumDigits(int i, int j) {
if (i / 10 == 0) {
return i % 10 + j;
}
return sumDigits(i / 10, j);
}
Output:
4
5
13
This thread on default parameters might help learn more as well.
Found a solution using String, not sure it's the best :
public int sumLastAndFirstDigit(Integer firstDigit, int number) {
String numberAsString = String.valueOf(number);
//Set the first digit
if(firstDigit == null) {
firstDigit = Integer.valueOf(numberAsString.substring(0,1));
//If there is only one digit in number for the first loop, then return 2 x firstDigit
if(numberAsString.length() == 1) {
return 2 * firstDigit;
}
}
//Remove the first digit to create the new number
String newNumberAsString = numberAsString.substring(1);
Integer newNumber = Integer.valueOf(newNumberAsString);
if(newNumberAsString.length() == 1) {
//When it's the last digit, sum first and last
return firstDigit + newNumber;
}
return sumLastAndFirstDigit(firstDigit, newNumber);
}
Then do :
sumLastAndFirstDigit(null,1234);
sumLastAndFirstDigit(null,137);
sumLastAndFirstDigit(null,4);
Use the sign as a flag to recognize the initial call. Only works with positive numbers, of course.
public static int sum(int value){
if(value > 0)
// initial call
return value % 10 + sum(-value);
else
// recursive call
return -value < 10 ? -value : sum(value / 10);
}
This are the 2 different solutions my professor suggested, although he said no helper (the first one is without an helper).
public static int sumFirstAndLast2(int num) {
if (num < 10 )
return num+num;
return sumFirstAndLast2(num/10) - num%100/10 + num%10;
}
public static int sumFirstAndLast(int num) {
if ( num < 10 )
return num+num;
return sumFirstAndLastHelper(num,true);
}
private static int sumFirstAndLastHelper(int num, boolean isLast) {
if ( isLast )
return num%10 + sumFirstAndLastHelper(num/10,false);
if ( num < 10 )
return num;
return sumFirstAndLastHelper(num/10,false);
}
I have two methods to find out prime number in java method - 2 working fine but getting wrong output from method one, can any help me where i did wrong in logic. Thanks in advance
My entire code
package prepare;
import java.util.Scanner;
public class Squar {
//Method - 1 to find prime number
boolean isPrime(int num){
int exp = (int)Math.sqrt(num);
for(int i=2;i<exp;i++){
if(exp%2==0){
return false;
}
}return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
Squar s = new Squar();
System.out.println("From M1 "+s.isPrime(num));
scan.close();
System.out.println("From M2 "+s.isPrimeNumber(num));
}
//Method - 2 to find prime number
public boolean isPrimeNumber(int number) {
if(number == 1){
return false;
}
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
for input : 63 actual out put would be false in prime number but getting
different output from method one
output
63
From M1 true
From M2 false
In isPrime() method, Shouldn't you be checking num % i == 0 rather than exp % 2 == 0?
Change isPrime function like this.
boolean isPrime(int num) {
int exp = (int) Math.sqrt(num);
for (int i = 2; i < exp; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
Because in if condition you are checking exp%2 == 0 . But this statement does not change when iterating on i < exp. So this logic should be on with num % i == 0
Have a look at this line of your code
if(exp%2==0){
it should be num % i
Well I think the culprit is
if(exp%2==0){
and it is causing a problem while iterating i<exp.So you may want to tweak it to
num%i==0
I have tried to give a few other approaches to this issue.
I hope that would be helpful.
I think there is a reason that tempted you to use
(int)Math.sqrt(num);
I have tried to elaborate it below.
Consider below 3 approaches.
All of them are correct but the first 2 approaches have some drawbacks.
Approach 1
boolean isPrime(int num) {
for(int i=2;i<num;i++) {
if(num%i==0)
return false;
}
return true;
}
We have a scope to make it faster.
Consider that if 2 divides some integer n, then (n/2) divides n as well.
This tells us we don't have to try out all integers from 2 to n.
Now we can modify our algorithm:
Approach 2
//checks whether an int is prime or not.
boolean isPrime(int num) {
for(int i=2;2*i<num;i++) {
if(num%i==0)
return false;
}
return true;
}
Finally, we know 2 is the "oddest" prime - it happens to be the only even prime number.
Because of this, we need only check 2 separately, then traverse odd numbers up to the square root of n.
I think this might have tempted you to use (int)Math.sqrt(num);
Approach 3
//checks whether an int is prime or not.
boolean isPrime(int num) {
//check if num is a multiple of 2
if (num%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=num;i+=2) {
if(num%i==0)
return false;
}
return true;
}
Hence, we've gone from checking every integer (up to n to find out that a number is prime) to just checking half of the integers up
to the square root.
Is it not an improvement, especially considering when numbers are large.
Well, your first algorithm is almost (replace %2 with %i) correct. I do not know the second algorithm, but i would definitely change it to this form:
public boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
I'm trying to solve this exercise: write a recursive method that returns the number of digits in the integer passed to it as an argument of type int. Allow for both positive and negative arguments. For example, -120 has three digits.
This is the code I have but I keep just getting 1 when I try to pass in 121:
public static int recursion(int inNumber){
//create a counter variable for the total of digits
int totalDigits = 0;
//base case
if (inNumber < -10 || inNumber > 10){
totalDigits++;
return totalDigits;
//recursive case
}else{
totalDigits++;
return recursion(inNumber/10) + totalDigits;
}
}
try this simplified code, using Math.abs
public static void main(String[] args) {
System.out.println(recursion(123456, 0));
}
public static int recursion(int inNumber, int totalDigits){
totalDigits++;
if (Math.abs(inNumber) < 10){
return totalDigits;
}else{
return recursion(inNumber/10, totalDigits);
}
}
output
6
So here is how I got through fixing this code:
1:
Solve the logical error and make your code more descriptive by using logical negation.
public static int recursion(int inNumber) {
//create a counter variable for the total of digits
int totalDigits = 0;
//base case
if (!(inNumber <= -10 || inNumber >= 10)) { //notice the !
return totalDigits + 1;
//recursive case
} else {
totalDigits++;
return recursion(inNumber / 10) + totalDigits;
}
}
Optimisation 1: Also you can get rid of the local variable totalDigits because it is always 1:
public static int recursion(int inNumber) {
//base case
if (!(inNumber <= -10 || inNumber >= 10)) {
return 1;
//recursive case
} else {
return recursion(inNumber / 10) + 1;
}
}
Optimisation 2: You can achieve the same using Math.abs(int) :
public static int recursion(int inNumber){
if (Math.abs(inNumber) < 10) { //base case
return 1;
} else { //recursive case
return recursion(inNumber / 10) + 1;
}
}
If you take 121,
int totalDigits = 0;
if (121< -10 || 121> 10){ // YES 121>10 then:
totalDigits++;
return totalDigits;
Your logic checks if it's higher than 10, which it is and returns totalDigits (1). What you wanna do is the inverse. If it's higher to 10, recall the same function. Basicly your if/else is just inversed.
every call of your method , you reset the value of totalDigits , you should affect totalDigits to your function as part of your recursive call, your code should be
public static int recursion(int inNumber) {
//create a counter variable for the total of digits
//base case
if (Math.abs(inNumber)<10) {
return 1;
//recursive case
} else {
return recursion(inNumber / 10) + 1;
}
}
Look again at your if condition. 121 is larger than 10, so the condition inNumber > 10 is true, totaldigits++ is executed and the method returns 1.
The condition should be if (inNumber > -10 && inNumber < 10) instead.
I need to write a boolean method called hasEight(), which takes an int as input and returns true if the number contains the digit 8 (e.g., 18, 808).
I don't want to use the "String conversion method".
I've tried the below code, but that only checks for the last digit.
import java.util.Scanner;
public class Verificare {
public static boolean hasEight(int numarVerificat) {
int rest = numarVerificat % 10;
return rest == 8;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Introduceti numarul pentru verificare: ");
int numar = keyboard.nextInt();
Verificare.hasEight(numar);
System.out.println("Afirmatia este: " + Verificare.hasEight(numar));
keyboard.close();
}
}
If you don't want to use string conversion methods then i think this method can be used.
public bool hasEight(int number)
{
while(number > 0)
{
if(number % 10 == 8)
return true;
number=number/10;
}
return false;
}
Use the below function.
boolean hasEight(int num) {
int rem;
while (num > 0) {
rem = num % 10;
if (rem == 8)
return true;
num = num / 10;
}
return false;
}
In every iteration of the loop, last digit of the number is retrieved (remainder when divided by 10). If it is 8, true is returned. Else, number is divided by 10 (integer division so that last digit is removed) and another iteration is started. When all digits are checked (8 or not), number becomes 0 and loop stops.
public static boolean hasEight(int numarVerificat)
{
while(numarVerificat > 0)
{
if(numarVerificat % 10 == 8)
break;
numarVerificat=numarVerificat/10;
}
return (numarVerificat>0);
}
From my homework, I need to have the user enter a number in numeric form, and convert it to the simultaneous fibonacci number from the sequence, while using recursion.
My question is how can I make the sequence through an array but not store it, so the array can be the size of the number the user entered...
Here's some starting code I have:
import java.util.Scanner;
public class ReverseUserInput1 {
//a recursive method to reverse the order of user input
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ReverseUserInput1 reverseIt = new ReverseUserInput1(); //creates new object
System.out.print("Program to convert a number to a fibonacci number,");
System.out.print(" - press Enter after each number. ");
System.out.println("- type \'0 or 1\' to finish the program.");
System.out.print(" --Enter a number: ");
int aNum = in.nextInt();
reverseIt.reverseInput(aNum); //invokes reverseInput() method
}
public static int reverseInput() {
if(aNum == 0) {
return aNum;
}
else if(aNum == 1) {
return aNum;
}
else {
reverseInput();
}
System.out.println(aNum);
}
}
Here is one method, note that this also includes the negafibonacci sequence;
private static Map<Integer, BigInteger> fibCache =
new HashMap<Integer, BigInteger>();
public static BigInteger fib(int n) {
// Uses the following identities, fib(0) = 0, fib(1) = 1 and fib(2) = 1
// All other values are calculated through recursion.
if (n > 0) {
// fib(1) and fib(2)
if (n == 1 || n == 2) {
return BigInteger.ONE;
}
synchronized (fibCache) {
if (fibCache.containsKey(n)) {
return fibCache.get(n);
}
BigInteger ret = fib(n - 2).add(fib(n - 1));
fibCache.put(n, ret);
return ret;
}
} else if (n == 0) {
// fib(0)
return BigInteger.ZERO;
}
if (n % 2 == 0) {
return fib(-n).multiply(BigInteger.ZERO.subtract(BigInteger.ONE));
}
return fib(-n);
}
public static void main(String[] args) throws Exception {
for (int x = -8; x <= 8; x++) {
System.out.println(fib(x));
}
}
Outputs
-21
13
-8
5
-3
2
-1
1
0
1
1
2
3
5
8
13
21
I was not going to post the actual algorithm (see my comment to his question earlier), but then I saw an unnecessarily complex version being posted. In contrast, I'll post the concise implementation. Note this one returns the sequence starting with 1,1,2. Another variant starts with 0,1,1,2 but is otherwise equivalent. The function assumes an input value of 1 or higher.
int fib(int n) {
if(n == 1 || n == 2) return 1;
return fib(n-2) + fib(n-1);
}
That's all.