How to reverse a number using recursion - java

I want to send in the recursion only the number itself and not more variables!!!
so, I made a code that make the operation but I don't have the stop point.
the code:
public static int upsideDown (int number) {
number += (number%10)*(Math.pow(10, String.valueOf(number).length()));
number %= 10;
return upsideDown (number);
}

You need to store the digit you are working with in a local variable instead of modifying number.
You need - instead of number %= 10 - to (integer) divide by 10 instead.
You need to multiply the previously stored digit by 10 raised to the power of string.length - 1; you need to add the result of this to the return value of the recursive call to upsideDown.
Actually, a for loop over length - 1, multiplying by 10 each time through the loop would be more efficient than using pow.
Exit code should simply be if (number == 0) return 0; at start of method.

Related

Can't create a method to make visible a words letters randomly

I am trying to create a method to make some of the word's letters visible and other ones *. This is actually a simple word guessing game. I ask the user to choose whether they want to give an answer or request a letter. For example if the answer is "ball" and user decides to request a word, ball should turn into "*a**".
That is the method I have came up with:
public static void showALetter(String correctAnswer) {
int randomLetterIndex = (int) Math.random() % (correctAnswer.length());
for (int i = 0; i < correctAnswer.length(); i++) {
if (i == randomLetterIndex) {
System.out.print(correctAnswer.charAt(randomLetterIndex));
} else {
System.out.print("*");
}
}
}
It only shows the first letter of the correct answer at every single request. What should I do ?
Math.random() returns a double with a value between zero and one (technically [0.0, 1.0) written as a mathematical interval). This is not what you want, so you instead need to use the newer java.util.Random class:
Random random = new Random();
int randomLetterIndex = random.nextInt(correctAnswer.length());
The random.nextInt(int limit) method will return a value from zero (inclusive) to limit (exclusive) which is what you need here for your puproses.
If you're going to use random numbers over and over again, then create your Random instance as a static class member and have your methods refer to that, so that you only create the object once.
Math.random() returns a number from zero to one. So, your randomLetterIndex will always be zero. Use this instead.
(int) (Math.random() * correctAnswer.length())
This will give a random number between 0 and correctAnswer.length() - 1.
Math.random() returns a double higher or equal than 0 and less then 1, (int) Math.random() will always return 0.
Use
(int)(Math.random() * correctAnswer.length())
The modulo is useless here, this way you always hit inside the given string as (int) cast returns the floor value so the result will never be equal or higher than correctAnswer.length().

return statement is giving unexpected result during implementation of the method to find power of ten

I was solving the question where we are given a integer and we have to return the greatest power of 10 which is smaller than or equal to the value of given int n.
i tried to solve it but the run time is not as expected.
public int powerofTen(int n){
int x;
if(n>0){
x = 1 + powerofTen(n/10);
}else{
return 0;
}
return x;
}
if i replace last return x , statement with return (int)Math.pow(10,x-1) to get the correct answer the value displayed is 0.
moreover if i try to use return x-1 instead of int x than too it shows 0.
a output for clearance:
if n = 100
with return x value is 3.
with return x-1 value is 0.
with return (int)Math.pow(10,x-1) the value is 0.
This does not have to do with recursion at all, the error is not in recursion code. The problem is that you need your function return e.g:
For input 100 the number 3 and probably return (int)Math.pow(10,x-1). If you replace return x with (int)Math.pow(10,x-1) then you will have wrong result in the recursion calls. For example you will call the function with input 100 which will call the function with input 10 and so on, but you expect the call of the function with input 10 to return to the outer call the value 1. If you place return x-1 (or (int)Math.pow(10,x-1) ) instead of return x then you will take result 0 instead of 1 in the recursion for input 10 and so you will get also 0 for input 100.
The error is logical, in order to solve the problem you need to find the exponent e.g for input 100 the number 3 and then return (outside from the function) (int)Math.pow(10,x-1) .
Even though it's already been replied, this way it's easier to see the steps to do in recursive algortihms:
base case: any number less than 10 returns 0 as greatest exponent for 10
recursive task: add 1 to the greatest exponent found for n/10
Some code:
public int powerofTen(int n){
if(n<10)
return 1;
else
return 10*powerofTen(n/10);
}

How can I reduce iterations in for loop that takes to much time for execution?

Here, I am finding number of perfect square numbers in given range.
But I am dealing with 'for' loop execution that takes much time for execution.
The index/key traverses from two numbers, lets say A to B, and does some operation in for loop.
The problem arises when there's large difference between A and B (e.g. A = 2 & B = 100000)
Can u suggest how can I reduce or optimize the execution time?
Scanner in = new Scanner(System.in);
int A = in.nextInt();
int B = in.nextInt();
int cnt = 0;
for(int number =A ; number<= B; number++){
int sqrt = (int) Math.sqrt(number);
if(sqrt*sqrt == number) {
cnt++;
}
}
System.out.println(cnt);
Or is it because of Math class operations that takes too much time to execute?
Can you suggest any alternate approach to find the square numbers between given range?
Thanks in advance!
I found an alternate way to find the count of perfect square numbers between given range.
This can be simply achieve by using Math.floor and Math.ceil operations.
Math.floor(Math.sqrt(B)) - Math.ceil(Math.sqrt(A)) + 1
Thanks! :)
Instead of going through each number in the range and figuring out if its a perfect square, I would suggest the below
Find a square root of the start number and find the integer part of it.
Lets say start number is 5. So integer part of the square root will be 2.
Now do the same for the range end number
Lets say end range was 1000, so the integer part of its square root would be 31. Now iterate from 2+1 to 31 and keep printing its square. That would give you the perfect squares between the given range.
Instead of the if(sqrt * sqrt == number) you could also check whether the double returned by Math.srt(number) is a integer. The algorithm would than become as follows:
for(int number =A ; number<= B; number++){
if((Math.sqrt(number) % 1) == 0) {
cnt++;
}
}
Note: Haven't tried the code myself so might not work as I expect.
Regarding the question on how you can improve the performance. The checking on whether the number is perfect could be done in parallel by executing per number a task. The access to the counter has to be synchronized than, (to be on the safe side).

Java, even number of even digits, odd number of odd digits

This program is essentially a game where the user must enter numbers to see which numbers are good: numbers with an even number of even digits, and an odd number of odd digits.
So first of all, the program ends when I enter a one digit number, which is not intentional. I assume that has something to do with the while being while (n > 0). There also is likely an issue with the if (numEven % 2 == 0......) because the print results seem almost random, with a number being good and the same number not being good sometimes.
Honestly, I am lost at this point. Thank you so much in advance for any help.
UPDATE: This code is working how I want it to, I just wanted to thank everybody who helped out! It's my first semester of computer science class, so I'm still rather new at this...excuse my mistakes that were likely pretty stupid :)
package quackygame;
import java.util.Scanner;
public class QuackyGame
{
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
int numEven = 0;
int numOdd = 0;
boolean isEven;
do
{
System.out.print("Enter a number > 0: ");
n = scan.nextInt();
while (n > 0)
{
if (n % 2 == 0)
{
//n is even
isEven = true;
numEven++;
}
else
{
//n is odd
isEven = false;
numOdd++;
}
n /= 10;
}
//if numEven is even and numOdd is odd
if (numEven % 2 == 0 && numOdd % 2 == 1)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n >= 0);
}
}
There are a few core issues in the code based on the desired results that you described. The most glaring issue I see is that you intend for the game to essentially "start from scratch" at the beginning of each round, but you never actually reset the numEven and numOdd variables. This is the source of your print results seeming random. For example, if you started a game and input the number:
34567
The game would process the number and say that it is a favorable number because it is odd, has an odd number of odd digits (3), and has an even number of even digits (2). However, upon playing the game again, it would execute the same code without setting the variables back to 0, which means that upon entering:
34567
The game would process this number as a bad number because the accumulated value of odd digits would be 6 instead of 3 (since 3 the first time + 3 the second time results in 6), and 6 is even. So what we want to do is this:
...
int n;
do
{
int numEven = 0;
int numOdd = 0;
System.out.print("Enter a number: ");
n = scan.nextInt();
...
By placing the numEven and numOdd declarations inside of the "do" block, they are local variables which only exist for the duration of the do block. We could also do something as simple as this:
...
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n > 0);
...
Just resetting the values will help us to keep track of the actual intended values of numOdd and numEven more consistently.
With regard to the program closing when you input a single digit number, I'm not sure. That doesn't make sense because since it is a do-while loop it should at least execute once, and issue one of the print statements. I'm loading this code into my IDE right now to give it a run through. I'll update my answer if I find something.
-EDIT-: Upon reading your question again, it seems that you may not be suggesting that the program closes before actually completing any of its functions, but simply that it closes at all. The reason for the closing of the program is that you are performing an integer division arithmetic function where you probably want to be using a different type of number. Let me explain:
In normal human counting, we have our natural set of numbers which have no decimal points. They usually start like this:
1, 2, 3, 4, 5 ...
Then we have a separate set of numbers for math where we operate with more precision:
0.5, 1.4232, 3.142 ...
When we are talking about numbers with normal human language, we assume that dividing 1 by 2 results in 0.5. However, computers do not implicitly know this. In order for a computer to reach the conclusion "0.5" from the division of 1 by 2, you need to explicitly tell it that it should use a certain type of number to produce that output.
The "normal" numbers I referenced earlier are most loosely related to the integer in programming. It's basically a number without a decimal point. What that means is that whenever you divide two integers together, you always get another integer as the result. So if you were to divide 1 by 2, the computer would not interpret the result as 0.5 because that number has a decimal. Instead, it would round it down to the nearest integer, which in this case is 0.
So for a more specific example referencing the actual question at hand, let's say we input the number 5 into our program. It goes through all of the calculations for odds and evens, but eventually gets to this line:
n /= 10
This is where things get funky. We are dividing two integers, but their result does not come out as a perfect integer. In this case, the result of 5 / 10 is again 0.5. But for the computer, since we are dividing two integers, the result 0.5 just won't do, so after rounding down to the nearest integer we get 0. At this point, there is one fatal mistake:
(while n > 0);
When we perform this check, we get false and the while loop ends. Why? Because after performing n /= 10, n becomes 0. And 0 is not greater than 0.
How can we fix this? The best thing to do is probably just use a floating point number to perform the calculations. In Java, this is pretty easy. All we really have to do is:
n /= 10.0
When Java sees that we are dividing by 10.0, which is not an integer, it automatically converts "n" to a floating point number to divide by 10.0. In this case then, if n is 5, our result in dividing 5 by 10.0 will be 0.5. Then, when we run:
(while n > 0);
This becomes true! And the loop does not break.
I am going to put all of these changes into my IDE just to confirm that everything is working as intended for me. I would suggest you give it a try too to see if it fixes your problems.
Hope this helps.
You are increasing numEven or numOdd count each time you input a number, and then you use if (numEven % 2 == 0 && numOdd % 2 == 1) , it is random because if you put number 33 for the first time => numOdd = 1; => true => "Wallace likes" , but next time you put 33 for the second time => numOdd = 2; => false => "Wallace doesnt like".
Edit* Maybe you wanted something like this?
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
boolean isEven;
do
{
System.out.print("Enter a number: ");
n = scan.nextInt();
//if 0, you leave the loop
if(n==0) {
System.out.println("You pressed 0, have a nice day");
break;
}
if (n % 2 == 0)
{
//it is even
isEven = true;
}
else
{
//it is not even
isEven = false;
}
//if even then he likes it, otherwise he does not
if (isEven)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
}
//put any contition here, lets say if you press 0 , you leave the loop
while (n != 0);
}

Java Method declaration

I'm trying to declare a method for my program that takes only a 5 digit integer and for each digit of the integer, reads a value from the program and prints it out. I understand this isn't very clear but im having trouble relaying what I mean. I understand it will be some sort of for loop to read each digit of the integer individually until something reaches 5. Something like the charAt() string method but works for digits.
Read up on "modulo". It is a primitive operation, available via the symbol % in Java.
For division, it is the remainder. So
System.out.println("Last digit: "+(12345 % 10));
will print 5. Figure out yourself how to get the other digits.
As an exercise, figure out how to print binary digits.
You can divide and take modulo.
while(n > 0) {
System.out.println("Digit " + (n % 10));
n /= 10;
}
This works fine if you are using any base: all you need to do is substitute 10 for the base (dividing by the base means shifting everything left, and taking the modulo means getting the last digit).
You can very easily convert your integer to a string and use charAt()
String parseableString = Integer.toString(yourInt);
for (int i = 0; i < parseableString.length(); i++){
System.out.println(parseableString.charAt(i));
}

Categories

Resources