How to check if a number contains a certain digit? - java

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);
}

Related

Why Does my Palindrome Code not work? My reverse variable does what it is supposed to but I dont get true even when it is printing out a palindrome

public class NumberPalindrome {
public static boolean isPalindrome(int number) {
int reverse = 0;
if (number<0){
number=number* -1;
}
while (number > 0) {
int lastDig = number % 10;
reverse = lastDig + reverse;
if (number<10) {break;}
reverse = reverse * 10 ;
number/=10;
}
if (number==reverse) {
return true;
}
return false;
}
}
why does my code not return true when I enter a palindrome number? I tried using it to print out the reverse value and it does it quite well, but just does not seem to get the boolean value straight though.
The problem was modifying the number variable, but then comparing it with the new generated reverse variable as if it was never edited.
Also, you were adding the last digit to the reverse variable before multiplying it by ten.
See the following code in Java:
public static boolean isPalindrome(int number) {
int reverse = 0;
if(number < 0) {
number *= -1;
}
int initialNumber = number;
while(number > 0) {
int lastDigit = number % 10;
reverse = (reverse * 10) + lastDigit;
if(number < 10) {
break;
}
number /= 10;
}
return initialNumber == reverse;
}
There are a few problems here. You need to save the original number for comparison with the the reversed number. The break statement confuses the logic.
To figure this out, I added some print statements to trace the progress. Adding print statements isn't elegant, but it is very useful.
Here is my version, with comments indicating what I changed.
public static boolean isPalindrome (int original)
{
// Need to save the original number for comparison
int number = original;
int reverse = 0;
if (number < 0)
{
number = number * -1;
}
while (number > 0)
{
int lastDig = number % 10;
// Update and shift reverse in one step
reverse = lastDig + reverse * 10;
number /= 10;
// Don't need extra break to terminate the loop
System.out.printf ("Check %d ; Reverse %d%n", number, reverse);
}
System.out.printf ("Final %d ; Reverse %d%n", number, reverse);
// Compare to original and return boolean value directly
return (original == reverse);
}

Sum of first and last digit in recursion

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);
}

Find Similar Integers Between Two Numbers

There are two number variables. I want to confirm and print similar integers between these two numbers. Eg. Int num1 = 6229; int num2 = 2394. I want the program to print the shared integers of '2' and '9' and return 'true' for confirmation.
public class Main {
public static void main(String[] args) {
System.out.println(hasSharedDigit(6229, 2394));
}
public static boolean hasSharedDigit(int firstNumber, int secondNumber) {
int firstDigit;
int secondDigit;
while ((firstNumber > 0) && (firstNumber < 10000)) {
firstDigit = firstNumber % 10;
firstNumber /= 10;
while ((secondNumber > 0) && (secondNumber < 10000)) {
secondDigit = secondNumber % 10;
secondNumber /= 10;
if (!(firstDigit == secondDigit)) {
continue;
}
System.out.println(secondDigit);
return true;
}
}
return false;
}
}
The DRY principle (Don't Repeat Yourself) guides you to move repeated code to a reusable helper method, so you should create a method that extracts the digits of a number into a Set, allowing you to easily use set intersection to find the digits they have in common.
For this, a BitSet is the most appropriate "Set", so you could write the helper method like this:
private static BitSet digitsOf(int number) {
BitSet digits = new BitSet(10);
do {
digits.set(number % 10);
} while ((number /= 10) != 0);
return digits;
}
Now it's very easy to find shard digits of two numbers:
public static boolean hasSharedDigit(int firstNumber, int secondNumber) {
BitSet digits = digitsOf(firstNumber);
digits.and(digitsOf(secondNumber));
System.out.println(digits);
return ! digits.isEmpty();
}
Test
System.out.println(hasSharedDigit(6229, 2394));
System.out.println(hasSharedDigit(0, 123));
System.out.println(hasSharedDigit(0, 404));
Output
{2, 9}
true
{}
false
{0}
true

Method that changes even digits to zero

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;
}
}

Determine Fibonacci Number from User Input using Recursion

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.

Categories

Resources