Return even numbers [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm a newbie here and just want to know how to return only even digits. And that without using while or for.
public static long evenDigit(long digit){
return ((digit < 10 && digit % 2 == 0)
|| ((digit % 10) % 2 == 0)
?
: evenDigit(digit / 10));
}
I'm getting a StackOverflowError. And I think it's because of the line behind the ?. It will recurse infinitely. I don't really know what to do right now. So maybe you guys have some tips?
edit: okay change the name of the method. Now it's probably more clear.
So this was btw a method from an exam last year. To print out only even digits. Using recursion. In this style.

From comment:
I have in the main method a system print out with the numbers: 123456
And I want only 246 to return.
First, you need to determine the stop condition, to ensure the recursion will terminate. If the input is only 1 digit, it shouldn't recurse:
if (number < 10) { // only one digit
if (number % 2 == 0)
return number; // keep even digit
return 0; // discard odd digit
}
Now, since number has multiple digits, we need to decide if we want to keep the last digit, then make recursive call on higher-order digits:
if (number % 2 != 0)
return odd(number / 10); // Discard last digit and process other digits
return odd(number / 10) * 10 // process other digits
+ number % 10; // keeping last digit
The above can be abbreviated to:
public static long odd(long number) {
return (number < 10 ? (number % 2 == 0 ? number : 0) :
number % 2 != 0 ? odd(number / 10) : odd(number / 10) * 10 + number % 10);
}

Related

How can I count integer occurrence when the int is 0 in java? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm a beginner in java and I made a program to count the number of times an int d occurs in a given integer n i.e n = 988, d = 8 returns 2.
It works with most cases (negative, positive, etc.) but my code says n = 0, d = 1 contains 1, which is wrong. How do I add a place to my 0 without making the integer 10 (which I erroneously do in my first if statement).
public class countingints{
public static int count(int n, int d) {
n = Math.abs(n);
if(n == 0) {
n = 10;
}
int result = 0;
while (n > 0) {
int place = n % 10;
if (place == d) {
result++;
}
n /= 10;
}
return result;
}
public static void main(String[] args) {
System.out.println(count(0, 1)); //SHOULD return 0
System.out.println(count(0, 5)); //returns 0
}
}
if(n == 0) {
n = 10;
}
```
Computer just follows instructions. If n is 0, n is set to 10, and 10 contains a single 1 digit.
If perhaps your intent with this if (n == 0) n = 10 line is to ensure that e.g. count(0, 0) returns 1, then just code that in: if (n == 0 && d == 0) return 1; - that's a weird case because mathematically speaking the question 'how many times does the digit 0 show up' is tricky. You can write 15 as 0015 as well, and in many ways, 0 is just a way of writing it, the number really can be considered just a completely blank string with no digits at all.
Point is, it's logical, more or less, that your algorithm does 'weird things' when you ask it for how many zeroes are in a number, in particular when you ask it how many zeroes are in the number 0. "Weird cases" usually mean they need hardcoding, so, do that.

Detecting 3 continuous odd or even number in an array [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
While I was practicing Java Problems on coding bat I came across the following problem statement:-
Problem:-
Given an array of integers, return true if the array contains either 3 even or 3 odd values all next to each other.
Example:-
modThree([2, 1, 3, 5]) → true
modThree([2, 1, 2, 5]) → false
modThree([2, 4, 2, 5]) → true
My Solution:-
public boolean modThree(int[] nums) {
for(int i=0; i<nums.length-2; i++){
if((nums[i] % 2 == 0 && nums[i+1] % 2 == 0 && nums[i+2] % 2 == 0) || (nums[i] % 2 == 1 && nums[i+1] % 2 == 1 && nums[i+2] % 2 == 1)){
return true;
}
}
return false;
}
Though my solution works, my solution looks a bit long(especially the if statement condition). So, I am looking for a solution with fewer lines of code. Can you help me with this?
The three modulo values must be equal, not necessarily 0 or 1 (although % 2 makes 0 and 1 the single possible results). Therefore, you can replace the if statement with:
if(nums[i]%2 == nums[i+1]%2 && nums[i]%2 == nums[i+2]%2) {
...
}

Understanding code to find the largest prime factor of a number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I found this code on an old youtube video and am having the hardest time understanding the logical sequence for the output. I was hoping any of you can help clarify.
Let's assume I pass a value of 21 to the getLargestPrime method.
In line 17 the conditional statement checks whether 21 % 2 != 0, that's True. So it carries another iteration of the code. But this time m = 3, which 21 % 3 != 0, that's actually False. Why is the code still executing the else statement? This is question #1.
Question #2
How can the if statement inside the else ever execute? When does number become == 1?
I know that this is probably super basic for you guys but for some reason I cannot follow the sequence in the output.
public class LargestPrime {
public static int getLargestPrime(int number){
if(number < 0){
return -1;
}
int m = 2;
int ans = 0;
int numbern;
if(number == 1){
System.out.println("This number is not a prime");
} else{
while (ans == 0){
if(number % m !=0){
m = m +1;
System.out.println(m + " value of m");
} else {
numbern = number;
number = number / m;
if(number == 1){
System.out.println(numbern + " is the largest prime factor of your number");
ans++;
}
}
}
} return number;
}
}
This is the output:
3 value of m
4 value of m
5 value of m
6 value of m
7 value of m
7 is the largest prime factor of your number
1
21%3!=0 returns false. Because of this the jvm executes the code after else. In e.g. 21%2!=0, that is true, it executes the code after if.
It is 1, if number is as m.
This is when your calculation gets to an end because there cannot be any more numbers after your number.

Making a basic algorithm [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
So basically I want to find a easier way to do this:
if(size == 2 || size == 6 || size == 10 || size == 14 || ...) unit /= 2;
So basically it start at 2 and then it check if equals to previous size + 4.
I need to go up to 256.
I want to know if there a easy way of doing this.
EDIT: Sorry I meant to do it all in one line, not multiple lines.
You may do this:
if ( size >= 2 && size <= 256 && size % 4 == 2 )
unit /= 2;
If it keeps getting raised by 4, you could try using module-4:
if ((size - 2) % 4 == 0 && size <= 256){
unit /= 2;
}
Or, if size can be negative but should be positive:
if ((size - 2) % 4 == 0 && size >= 0 && size <= 256){
unit /= 2;
}
You could possibly do it with a switch statement as follows:
switch(size) {
case 2:
unit /=2;
case 4:
unit /= 2;
....
}
but this is still cumbersome. Another alternative could be:
for(int i=2; i < 256; i+=4) {
if (size == i) {
unit /= 4;
}
}
I'd just use an array of possible divisors.
Extend this into a class if the number to be divided by changes.
Derive the divisor on the fly if there is a mathematical progression of some kind (such as d[n+1] = d[n] + 4).
int[] divisors = {2, 6, 10};
int doIt(int n, int unit) {
for (int i : divisors) {
if (n == i) {
unit /= 2;
}
}
return unit;
}
You can ace this in O(1) with
if ((size - 2) % 4 == 0){
/*2, 6, 10 etc*/
unit >>= (Math.min(size, 256) + 2) / 4;
}
where the bitwise shift generates the appropriate multiplication of a power of two: a touchstone for your knowledge of operator precedences.
Now the question has been updated, the operation on unit is the considerably duller unit /= 2, and you'll have to add in the newly-introduced upper-bound on size of 256.
A cryptic way of doing it:
unit >>= ((size & -253) == 2) ? 1 : 0;
Explanation:
A number in the range 2-254 is also in the range 0-255. You can do a bitwise AND with ~255 = 0xffffff00; if the value is non-zero, it is outside that range;
To check calculate number % 4, do a bitwise AND with 3; compare this to 2 to see if number % 4 == 2.
So, to check if a number meets both of these criteria, we can calculate the bitwise AND of size with the bitwise AND of the two bit masks above: if both conditions are met, the result is 2.
Hence:
(size & (~255 | 3)) == 2 (simplifies to) (size & -253) == 2.

Java - Print last digit of a number as well as the digit before [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
If I want to print the last digit of a number (say 16), I use: number % 10 and the output is 6. If I want to print the digit before the last, I may divide the number by 10 and cast to int. This only applies for numbers! If I want to obtain the digit preceding 6, I would definitely obtain 0, but the challenge is to obtain the same digit and not 0. How is that?
A simple implementation could look like this:
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
public static void main(String[] args) {
System.out.println(getNthNumber(-16, -14)); // 1
System.out.println(getNthNumber(16, -14)); // 1
System.out.println(getNthNumber(16, 0)); // 1
System.out.println(getNthNumber(16, 1)); // 6
System.out.println(getNthNumber(16, 4)); // 6
System.out.println(getNthNumber(12345678, 4)); // 5
}
static int getNthNumber(final int pNumber, final int pIndex) {
final String numberString = Integer.toString(abs(pNumber));
return numberString.charAt(max(0, min(pIndex, numberString.length() - 1))) - '0';
}
I'm not sure, but I think that you are confused by something. This is the straight-forward mathematical way:
int i = 16;
int lastDigit = i % 10;
int precedingDigit = (i / 10) % 10;
In Java, when you do integer division, the result is always rounded towards zero.
For the example you provided, in case of 5. Where you wanted to get the same digit twice:
int i = 5;
int lastDigit = i % 10;
int precedingDigit = (i == lastDigit) ? lastDigit : ((i / 10) % 10);

Categories

Resources