public static boolean sameNumbers(int number) {
boolean isSame;
isSame = (number % 10) == (number / 10) % 10;
sameNumbers(number / 10);
return isSame;
}
My task is to implement a method which checks if the given int value has all the same numbers (e.g. 666 or 1111). However, the requirement is that I should just choose recursion and no iteration.
I am aware that my method wouldn't work, but I really don't know how I can solve this problem without any if statements. Any ideas?
You have the right approach. It's just a matter of combining the base case with the recursive component. If you want to avoid if, just do this:
public static boolean sameNumbers(int number) {
return number < 10 || ((number % 10) == (number / 10) % 10)
&& sameNumbers(number / 10));
}
When tackling a recursion problem, you have to split it into a base case and a recurse case. So for instance, you know that any number with one digit contains all the same digit. That would be your base case.
For numbers with more than one digit, you could check two digits, and fail fast if they don't match. If they do match, then chop one off and return the test against the shortened number.
For a more spelled out implementation:
public static bool sameNumbers(int number) {
int onesPlace = number % 10;
int shifted = number / 10;
int tensPlace = shifted % 10;
return onesPlace == number || (onesPlace == tensPlace && sameNumbers(shifted));
}
Depending on your definition of correct, this will handle negative numbers correctly.
If you are allowed to use if statements, this will save you a few instructions:
public static bool sameNumbers(int number) {
int onesPlace = number % 10;
if (onesPlace == number) {
return true;
}
int shifted = number / 10;
int tensPlace = shifted % 10;
return onesPlace == tensPlace && sameNumbers(shifted);
}
Related
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
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);
}
}
I have this exercise that asks me to create a program to count the odd digits of a number, so if the number is 12345 it will count to 3, because of 1, 3 and 5. I started creating a recursive method, my very first one, with a ramified if-else. The point of using it was to see if (inputNumber % 2 == '0'). If yes, the last digit of the number would be a 0, 2, 4, 6 or 8, because only those digits give 0 if moduled by 2, so oddDigitsCounter wouldn't grow. Else, if (inputNumber % 2 == '1'), the last digit of the number would be 1, 3, 5, 7 or 9. oddDigitCounter++;, so. To check digit by digit I tried to divide the number by ten because it is a int variable, so it doesn't saves any digit after the floating point.
This is the method since now:
public static int oddDigitCounter (int number) {
int oddCount, moduledNumber, dividedNumber, absoluteInput;
oddCount = 0;
absoluteInput = Math.abs(number);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == '0') {
oddCount = oddCount; }
else if (moduledNumber == '0') {
oddCount = oddCount;
oddDigitCounter(dividedNumber); }
else // (number % 2 != 0)
oddCount++;
oddDigitCounter(dividedNumber); }
return oddCount;
Why it gives me an infinite recursion? What's wrong? Why? Any other way to solve this? Any idea for improving my program?
You don't use the result of the recursive call. You also compared a integer to the character '0', which is not the same as comparing to 0.
public static int oddDigitCounter (int number)
{
int moduledNumber, dividedNumber, absoluteInput;
inputAssoluto = Math.abs(numero);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == 0) {
return 0;
}
else if (moduledNumber == 0) {
return oddDigitCounter(dividedNumber);
}
else {
return 1 + oddDigitCounter(dividedNumber);
}
}
Declare odd counter outside of recursion and you should get results :
static int oddCounts;
public static int oddDigitCounter(int number) {
int moduledNumber, dividedNumber, absoluteInput = 0;
absoluteInput = Math.abs(number);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == 0) {
return 0;
} else if (moduledNumber == 0) {
return oddDigitCounter(dividedNumber);
} else {
oddCounts++;
return 1 + oddDigitCounter(dividedNumber);
}
}
As mentioned in the comments, you should compare to 0 and not to '0'. The latter will be interpreted as 48, the ASCII character for the numeral zero.
Furthermore, absoluteInput is never assigned to and will always have its initial value 0. Where does inputAssoluto come from?
Wouldn't you want to list your numbers and then check each one as a single int again, meaning you can check digit by digit and don't have to divide the number by ten.
a very short solution will then suffice: (if your passing the number as a string the LINQ one-liner can give you what you want).
static int OddDigitCounter(int numbers)
{
var c = numbers.ToString();
var oddcount = c.Count(no => int.Parse(no.ToString()) % 2 != 0); //<--one liner
return oddcount;
}
I've beeen trying to get a program written for a lab for class, and I believe I almost have it, but it won't add up the divisors (div in the code) to the sum and return true if it is a perfect number and false otherwise. My code compiles and runs fine but will only return a false, presumably because sum is staying at 1 (it initializes at one since 1 is a divisor of every number). number is a private int brought in from the constructors and set statements.
public boolean isPerfect()
{
int x = number -1 ;
int div = 0;
int sum = 1;
while(x> 1)
{
if(number % x == 0)
{
div = x;
sum=+ div;
}
x--;
}
if(sum == number)
{
return true;
}
else
{
return false;
}
}
This is backwards. sum =+ div; should be sum += div;
What you have is basically sum = (+div), in other words positive div.
As well as the += / =+ issue, your code also says that 1 is a perfect number, which is incorrect (6 is the first perfect number). This is because you start with a sum of 1, the loop won't execute at all, then you compare sum and number, which are equal for 1. You could just add a check for this special case, e.g.
if(sum == number && number > 1)...
Additional tip - instead of :
if(sum == number)
{
return true;
}
else
{
return false;
}
You can just use:
return (sum == number);
You could have sum= sum + div; or sum += div;
also where is your number variable define i guess it is something like public boolean isPerfect(int number)
How would I determine whether a given number is even or odd? I've been wanting to figure this out for a long time now and haven't gotten anywhere.
You can use the modulus operator, but that can be slow. If it's an integer, you can do:
if ( (x & 1) == 0 ) { even... } else { odd... }
This is because the low bit will always be set on an odd number.
if ((x % 2) == 0) {
// even
} else {
// odd
}
If the remainder when you divide by 2 is 0, it's even. % is the operator to get a remainder.
The remainder operator, %, will give you the remainder after dividing by a number.
So n % 2 == 0 will be true if n is even and false if n is odd.
Every even number is divisible by two, regardless of if it's a decimal (but the decimal, if present, must also be even). So you can use the % (modulo) operator, which divides the number on the left by the number on the right and returns the remainder...
boolean isEven(double num) { return ((num % 2) == 0); }
I would recommend
Java Puzzlers: Traps, Pitfalls, and Corner Cases Book by Joshua Bloch
and Neal Gafter
There is a briefly explanation how to check if number is odd.
First try is something similar what #AseemYadav tried:
public static boolean isOdd(int i) {
return i % 2 == 1;
}
but as was mentioned in book:
when the remainder operation returns a nonzero result, it has the same
sign as its left operand
so generally when we have negative odd number then instead of 1 we'll get -1 as result of i%2. So we can use #Camilo solution or just do:
public static boolean isOdd(int i) {
return i % 2 != 0;
}
but generally the fastest solution is using AND operator like #lucasmo write above:
public static boolean isOdd(int i) {
return (i & 1) != 0;
}
#Edit
It also worth to point Math.floorMod(int x, int y); which deals good with negative the dividend but also can return -1 if the divisor is negative
Least significant bit (rightmost) can be used to check if the number is even or odd.
For all Odd numbers, rightmost bit is always 1 in binary representation.
public static boolean checkOdd(long number){
return ((number & 0x1) == 1);
}
Works for positive or negative numbers
int start = -3;
int end = 6;
for (int val = start; val < end; val++)
{
// Condition to Check Even, Not condition (!) will give Odd number
if (val % 2 == 0)
{
System.out.println("Even" + val);
}
else
{
System.out.println("Odd" + val);
}
}
If the modulus of the given number is equal to zero, the number is even else odd number. Below is the method that does that:
public void evenOrOddNumber(int number) {
if (number % 2 == 0) {
System.out.println("Number is Even");
} else {
System.out.println("Number is odd");
}
}
This following program can handle large numbers ( number of digits greater than 20 )
package com.isEven.java;
import java.util.Scanner;
public class isEvenValuate{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String digit = in.next();
int y = Character.getNumericValue(digit.charAt(digit.length()-1));
boolean isEven = (y&1)==0;
if(isEven)
System.out.println("Even");
else
System.out.println("Odd");
}
}
Here is the output ::
122873215981652362153862153872138721637272
Even
/**
* Check if a number is even or not using modulus operator.
*
* #param number the number to be checked.
* #return {#code true} if the given number is even, otherwise {#code false}.
*/
public static boolean isEven(int number) {
return number % 2 == 0;
}
/**
* Check if a number is even or not using & operator.
*
* #param number the number to be checked.
* #return {#code true} if the given number is even, otherwise {#code false}.
*/
public static boolean isEvenFaster(int number) {
return (number & 1) == 0;
}
source
You can use the modulus operator, but that can be slow. A more efficient way would be to check the lowest bit because that determines whether a number is even or odd. The code would look something like this:
public static void main(String[] args) {
System.out.println("Enter a number to check if it is even or odd");
System.out.println("Your number is " + (((new Scanner(System.in).nextInt() & 1) == 0) ? "even" : "odd"));
}
You can do like this:
boolean is_odd(int n) {
return n % 2 == 1 || n % 2 == -1;
}
This is because Java has in its modulo operation the sign of the dividend, the left side: n.
So for negatives and positives dividends, the modulo has the sign of them.
Of course, the bitwise operation is faster and optimized, simply document the line of code with two or three short words, which does it for readability.
Another easy way to do it without using if/else condition (works for both positive and negative numbers):
int n = 8;
List<String> messages = Arrays.asList("even", "odd");
System.out.println(messages.get(Math.abs(n%2)));
For an Odd no., the expression will return '1' as remainder, giving
messages.get(1) = 'odd' and hence printing 'odd'
else, 'even' is printed when the expression comes up with result '0'
package isevenodd;
import java.util.Scanner;
public class IsEvenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number: ");
int y = scan.nextInt();
boolean isEven = (y % 2 == 0) ? true : false;
String x = (isEven) ? "even" : "odd";
System.out.println("Your number is " + x);
}
}
Here is full example:-
import java.text.ParseException;
public class TestOddEvenExample {
public static void main(String args[]) throws ParseException {
int x = 24;
oddEvenChecker(x);
int xx = 3;
oddEvenChecker(xx);
}
static void oddEvenChecker(int x) {
if (x % 2 == 0)
System.out.println("You entered an even number." + x);
else
System.out.println("You entered an odd number." + x);
}
}