Finding Whether Two Numbers Share a Digit - java

I am working on this problem where I am supposed to use loops to find whether two numbers share a digit. The code I wrote does not return true if the shared digit is the first digit of a number. I can not find the bug in my code or any other solution. Please help!
public static boolean hasSharedDigit(int firstNumber, int secondNumber) {
if ((firstNumber < 10 || firstNumber > 99) || (secondNumber < 10 || secondNumber > 99)) {
return false;
}
int testFirstNumber = firstNumber;
int testSecondNumber = secondNumber;
while (testFirstNumber != 0) {
while (testSecondNumber != 0) {
if ((testFirstNumber % 10) == (testSecondNumber % 10)) {
return true;
}
testSecondNumber /= 10;
}
testFirstNumber /= 10;
}
return false;
}

You should reset testSecondNumber before the next testFirstNummber loop.
In your code, the inner loop is called only once, because testSecondNumber goes to 0 and is not reset.
The right solution is:
public static boolean hasSharedDigit(int firstNumber, int secondNumber) {
if ((firstNumber < 10 || firstNumber > 99) || (secondNumber < 10 || secondNumber > 99)) {
return false;
}
int testFirstNumber = firstNumber;
while (testFirstNumber != 0) {
int testSecondNumber = secondNumber;
while (testSecondNumber != 0) {
if ((testFirstNumber % 10) == (testSecondNumber % 10)) {
return true;
}
testSecondNumber /= 10;
}
testFirstNumber /= 10;
}
return false;
}

It seems that offered solution checks only 2-digit numbers so the performance is not the issue in this case and using nested loop should not have any serious impact.
However, if a common digit needs to be found for any integer numbers (not only positive), it would be better to use a small array to count digits in the first number and then verify if a digit from the 2nd number is present in this array without using nested loops.
static boolean commonDigits(int xx, int yy) {
// handle negative values
int x = Math.abs(xx);
int y = Math.abs(yy);
int[] digits = new int[10];
if (x == 0) { // handle 0
digits[0]++;
}
while (x > 0) {
digits[x % 10]++;
x /= 10;
}
// check for 0
if (y == 0 && digits[0] > 0) {
return true;
}
while (y > 0) {
if (digits[y % 10] > 0) {
return true;
}
y /= 10;
}
return false;
}
A shorter version based on converting a number into stream of characters via conversion to String may look like this:
static boolean commonDigitsStream(int x, int y) {
int[] digits = new int[10];
Integer.toString(Math.abs(x))
.chars()
.map(i -> i - '0')
.forEach(i -> digits[i]++);
return Integer.toString(Math.abs(y))
.chars()
.map(i -> i - '0')
.anyMatch(i -> digits[i] > 0);
}

Related

guys any possible refractory code for the above code

Guys I want to modify this if or block so dynamically it divide the value x based on what or condition got executed.
public boolean isUgly(int n) {
boolean isUgly=true;
while(n>0)
{
if(n%2==0||n%3==0||n%5==0)
{
n = n/x //<-------- here i want x should be based on the if condition where or is true
}
else {
isUgly=false;
break;
}
}
return isUgly;
}
You looking for something like this?
public static boolean isUgly(int n) {
final int[] uglyPrimes = {2, 3, 5};
boolean isUgly = true;
while (n > 1 && isUgly) {
isUgly = false;
for (int x : uglyPrimes) {
if (n % x == 0) {
n = n / x;
isUgly = true;
}
}
}
return isUgly;
}
Of course, I would just implement it like this:
public static boolean isUgly(int n) {
while (n > 1 && n % 2 == 0)
n /= 2;
while (n > 1 && n % 3 == 0)
n /= 3;
while (n > 1 && n % 5 == 0)
n /= 5;
return (n <= 1);
}
Or this:
public static boolean isUgly(int n) {
for (int x : new int[] { 2, 3, 5 })
while (n > 1 && n % x == 0)
n /= x;
return (n <= 1);
}
All 3 solutions really should have the following added to the beginning of the method, but that's outside the scope of the challenge:
if (n <= 0)
throw new IllegalArgumentException("Invalid value: " + n);
Try the following code, in this way you can divide n depending on the condition, but this method will always return false as in any case, it will execute the else statement for sure. What is your goal?
public boolean isUgly(int n)
{
boolean isUgly=true;
while(n>0)
{
if(n%2==0)
{
n = n/2;
}
else if(n%3==0)
{
n = n/3;
}
else if(n%5==0)
{
n = n/5;
}
else
{
isUgly=false;
break;
}
}
return isUgly;
}

Java C double the value of the every even position of the value and sum up issue

I want to ask about what mistake I had make because i want to sum up the value in the odd position into Sumlast variable and the sum of even position value into Sumlastwo variable.
However I am required to double up the every value in even position then separate them into 2 digit like 9X2 = 18 ---> 1+8
For the odd value have no issue but when it reach the even position there is some issue.
Example I had did the input : 81
Output:
7
1
But when I type more digit like :9181
it become output:
27
2
it suppose to be (9X2) , (8X2) --> 18 , 16 = 1+8+1+6 = 16
output:
16
2
public static void main(String[] args) {
int c = 1;
int Sumlast = 0;
int Sumlasttwo = 0;
int numeven = 0;
Scanner myscanner = new Scanner(System.in);
System.out.print("Please enter your 8 digit number credit card: ");
String num = myscanner.nextLine();
if(num.length() != 8) //check the number of digit is 8
{
int test = Integer.parseInt(num);
while(test != 0)
{
if(c%2 == 0) //even
{
numeven = test * 2;
while(numeven > 0)
{
Sumlasttwo += (numeven%10);
numeven /= 10;
}
}
else //odd
{
Sumlast += test%10;
}
test /= 10;
c++;
}
System.out.println(Sumlasttwo);
System.out.println(Sumlast);
}
}
You forgot to take the digit from test in the even-case.
int test = Integer.parseInt(num);
while (test != 0)
{
int digit = test % 10;
if (c % 2 == 0) //even
{
int numeven = digit * 2;
while (numeven > 0)
{
Sumlasttwo += numeven % 10;
numeven /= 10;
}
}
else //odd
{
Sumlast += digit;
}
test /= 10;
c++;
}
Also it is more readable to declare numeven as near to its usage as possible.
Sumlast in java conventionally is written sumLast. Also } else { and ...) { is such a convention, but for instance not in C, and not as holy as camel-case names.
Debugging would have helped.
Using a help method would have made the code better:
boolean even = true;
while (test != 0) {
int digit = test % 10;
if (even) {
sumEven += digitsSum(digit * 2);
} else {
sumOdd += digit;
}
test /= 10;
even = !even;
}
private static void digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}

How to determine if an inputted integer contains certain digits without using strings

In this program I am supposed to figure out if the integer that the user enters contains a certain digit (in this case 7 and 3), and then return a boolean. So far I have:
public static boolean contains(int num, int x) {
Scanner input = new Scanner(System.in);
int currentLength = numberDigits(num); //method that counts the number of digits in the inputed integer
int digit; // current first digit
int firstNumber = firstNum(num);
boolean digitTrue = false;
while (currentLength > 0 ) {
digit = firstNumber;
if (num == x)
{
digitTrue= true;
} else {
digitTrue= false;
}
}
return digitTrue;
}
By invoking module 10 on a number you retrieve the last digit of this number.
Perform it on num, then perform it on num/10, then on num/100 until you iterates on all digits (that is while the division result > 0).
You could so write :
int currentNumber = num;
while (currentNumber > 0 ) {
if (currentNumber % 10 == x){
return true;
}
currentNumber = currentNumber / 10;
}
return false;
Note that the boolean variable is helpless.
You want to return true as soon as a digit equals to x, so return true directly in the conditional statement block and return false; after the while statement.
This code works correctly for contains (0, 0) too:
boolean contains (int num, int x) {
do {
if (num % 10 == x){
return true;
}
num /= 10;
} while (num > 0);
return false;
}
For x > 9 or x < 0, you have to write an guard statement and for num (and/or x) < 0 you should take the Math.abs first.
The best way to solve this that I know of is to use %. % or Modulus returns the remainder of one number / by another number. For example 5 % 2 = 1 or 355 % 10 = 5. If you are looking only to check a large number for single digit numbers I would suggest this method
public static boolean contains(int num, int x){
while(num >= 0){
if (num % 10 == x){
return true;
}
if (num > 0){
num = num / 10;
}else{
return false;
}
}
return false;
}
Hope this Helps

Codingbat- Recursion1- count7

Can anybody help me programming the next problem (taken from Codingbat- Recursion1- count7)
Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
count7(717) → 2
count7(7) → 1
count7(123) → 0
There are some solutions which includes number of "returns".
I would like to program the problem with only 1 "return".
Well here's the solution I wrote and let's see how to do it with only one return
public int count7(int n)
{
int c = 0;
if (7 > n)
{
return 0;
}
else
{
if ( 7 == n % 10)
{
c = 1;
}
else
{
c = 0;
}
}
return c + count7(n / 10);
}
the same with only one return
public int count7(int n)
{
return (7 > n) ? 0 : ( ( 7 == n % 10) ? 1 + count7(n / 10) : 0 + count7(n / 10));
}
public int count7(int n) {
int counter = 0;
if( n % 10 == 7) counter++;
if( n / 10 == 0) return counter;
return counter + count7(n/10);
}
Sure PFB my solution in JAVA for the same
public int count7(int n) {
if((n / 10 == 0) && !(n % 10 == 7)) //First BASE CASE when the left most digit is 7 return 1
return 0;
else if((n / 10 == 0) && (n % 10 == 7)) //Second BASE CASE when the left most digit is 7 return 0
return 1;
else if((n % 10 == 7))
//if the number having 2 digits then test the rightmost digit and trigger recursion trimming it there
return 1 + count7(n / 10);
return count7(n / 10);
}
public int count7(int n) {
if(n == 0)
return 0;
else{
if(n%10 ==7)
return 1+count7(n/10);
return 0+count7(n/10);
}
}
public static int count7(int n){
if(n == 7)
return 1;
else if(n > 9){
int a = count7(n%10);
int b = count7(n/10);
return a + b;
}else
return 0;
}
public int count7(int n)
{
if(n==0)return 0;
if(n%10==7)return 1+count7(n/10);
else return count7(n/10);
}
public int count7(int n) {
if (n != 7 && n < 10) return 0;
else if (n == 7) return 1;
else if (n%10 == 7) return count7(n/10) + 1 ;
else return count7(n/10);
}
public int count7(int n){
if(n < 7)
return 0;
else if(n % 10 == 7)
return 1 + count7(n / 10);
else
return count7(n / 10);
}
the first if-statement is the base case that we would want to terminate on. The second checks to see if the rightmost digit is 7. If it is, chop the rightmost digit off and try again. When the recursive calls terminate and and values start getting returned up the chain, add 1 to include this successful check. In the case that neither of the above statements are true, chop off the rightmost digit and try again.
I know this is 2 years old, but hope this is a bit more readable and intuitive, and thus helpful.
Here is how I did it.
public int count7(int n) {
return (n==0?0:(count7(n/10)+(n%10==7?1:0)));
}
Recursion goes to 0 and it returns 0, when it comes back out checks if each number is 7, returns 1 if it is else 0. It continues adding those until all the way out.
Using one return will likely make it harder to read. If you are counting occurrences in recursion, an easy formula is to create a base case to terminate on, then provide an incremental return, and finally a return that will aid in reaching the base case without incrementing. For example..
public int count7(int n) {
if(n == 0) return 0;
if(n % 10 == 7) return 1 + count7(n / 10);
return count7(n / 10);
}
Using a one liner return like the one below in my opinion is harder to read or update because of the double ternary..
public int count7(int n)
{
return (n == 0) ? 0 : (n % 10 == 7) ? 1 + count7(n / 10) : count7(n / 10);
}
My solution works backwards from the nth digit to the first digit, by taking the modulus of the input. we add the number of sevens found into the return, for the final output.
Then checking whether the input is less than 7 can be the next step. If the input is less than 7 then there have never been any 7s in the input to begin with.
public int count7(int n) {
int sevens_found = 0;
if( n % 10 == 7 ) sevens_found ++;
return ( n < 7) ? 0 : ( n % 10 == 7 ) ? sevens_found + count7 ( n / 10 ) : count7 ( n / 10 );
}
#include<bits/stdc++.h>
using namespace std;
int count_occurences(int k){
int r;
if(k==0){
return 0;
}
r = k%10;
k = k/10;
if(r!=7){
return count_occurences(k);
}
return 1+count_occurences(k);
}
int main()
{
int x;
cin>>x;
cout<<" "<<count_occurences(x);
return 0;
}
public int count7(int n) {
int length = 0;
int counter = 0;
if ((n / 10) * 10 != n || (n / 10) != 0) {
if (n % 10 != 7) {
counter++;
}
length += 1 + count7(n / 10);
}
return length - counter;
}
The base case of n == 0 just "breaks" us out of the recursive loop, the n % 10 == 7 allows us to actually count the amount of 7s in an integer, and the return statement iterates through the given argument.
public int count7(int n) {
if (n == 0)
return 0;
if (n % 10 == 7)
return 1 + count7(n / 10);
return count7(n / 10);
}
public int count7(int n)
{
return occurrencesCounting(n, 0);
}
private int occurrencesCounting(int n, int count)
{
int counter = n % 10 == 7 ? count + 1 : count;
if (n / 10 == 0)
{
return counter;
}
return occurrencesCounting(n / 10, counter );
}

finding the sum of number dividsable by x using recursion

I want to find the sum of numbers that is divisible by x using recursive method
Ex if n= 10, x=3, the code should return sum of 3+6+9
Write a recursive method sumDivByX(n, x), which finds the sum of all
numbers from 0 to n that are divisible by x.
I asked my teacher about it and he told me "Firstly, total should be global. You should return 0 if n or x == 0. I only care if n is divisible by x. So I only add n to total (total+=n) if (n%x==0) otherwise do nothing. And do recursion sumDivByX(n-1,x) and return total as usual." I tried to correct it.
public static int sumDivByX(int n, int x) {
int total = 0;
if (n == 0 || x == 0) {
return -1;
}
if (n % x >= 1) {
return total = 0;
} else if (n % x == 0) {
return total += n;
}
return total + sumDivByX(n - 1, x);
}
When I run the program I get 0.
Eliminate the returns inside your second and third if statements
public static int sumDivByX(int n, int x) {
int total = 0;
if (n == 0 || x == 0) {
return 0;
}
if (n % x >= 1) {
total = 0;
} else if (n % x == 0) {
total += n;
}
return total + sumDivByX(n - 1, x);
}
For a cuter, more compact version
public static int sumDivByX(int n, int x) {
if (n == 0 || x == 0) {
return 0;
}
return (n % x == 0 ? n : 0) + sumDivByX(n - 1, x);
}
Note - depending on the semantics you intend, you might want to have separate checks for x<=0 (possibly and error?) and n==0 (base case).
Step through your code and you'll see that it never recurses when n ==10 and x==3, since (10 % 3 == 1)
When a method gets to a "return" statement it ends, in your case at the second if.
Your total is initialized by 0 everytime the method runs, so you should consider making it global.
Your method generates an exception if you try to use negative numbers as paramethers
Try this:
int total=0;
public static int subDivByX(int n, int X) {
if (n>0 && x>0) {
if (n%x==0){
total += n;
}
return sumDivByX(n-1,x);
}
else return -1;
}
This seems to work
private static int sumDivByX(int n,int x) {
if (n < x || x < 1 ) {
return 0;
}
int d = n/x;
return (x * d) + sumDivByX(n - x , x);
}
Recursion could cause a stackoverflow.

Categories