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
Related
I'm learning Java, and I'm stuck on a recursion problem.
I need to use a recursive method to check if a number is an Armstrong number or not.
My code:
public class ArmstrongChecker {
public boolean isArmstrong(int number) {
// check if the number is a negative number
if (number < 0) {
return false;
}
ArmstrongChecker armstrongChecker = new ArmstrongChecker();
// find the length of the number
int length = armstrongChecker.lengthChecker(number);
// create a variable to store the sum of the digits of the number
int sum = 0;
// find the individual digits and raise to the power of the numbers of digits
if (number != 0) {
int digit = Math.floorMod(number, 10);
int powerRaised = (int) Math.pow(digit, length);
sum = sum + powerRaised;
isArmstrong(number / 10);
}
return sum == number;
}
// method to check the length of the number
public int lengthChecker(int number) {
int length = String.valueOf(number).length();
return length;
}
}
How do I prevent int length in isArmstrong() method from changing its value.
While you are not changing it's value in the posted code, you could mark that variable to be a constant. This way the compiler can error out if you tried to assign a new value.
final int length = armstrongChecker.lengthChecker(number);
As I've already said in the comments, your solution has the following issues:
The result of the recursive call isArmstrong() is being ignored;
There's no need for spawning new instances of ArmstrongChecker. And this method doesn't require object creation at all, it can be implemented as static.
Checking if the number is an Armstrong number boils down to calculating its Armstrong sum, the solution will be cleaner if you implement only this part using recursion.
It might look like this:
public static boolean isArmstrong(int number) {
if (number < 0) return false;
if (number < 10) return true;
return number == getArmstrongSum(number, String.valueOf(number).length());
}
public static int getArmstrongSum(int number, int power) {
if (number == 0) {
return 0;
}
return (int) Math.pow(number % 10, power) + getArmstrongSum(number / 10, power);
}
main()
public static void main(String[] args) {
System.out.println(isArmstrong(370)); // true
System.out.println(isArmstrong(12)); // false
System.out.println(isArmstrong(54)); // false
System.out.println(isArmstrong(153)); // true
}
Output:
true
false
false
true
You need to get the length once for whole recursion, so the cleanest approach would be to pass down both the number and the length into the recursion. An easy way to do this is to have one method that is the public face of the API, and another that does the recursion.
public class ArmstrongChecker {
public boolean isArmstrong(int number) {
if (number < 0) {
return false;
}
int length = lengthChecker(number);
int sum = armstrongSum(number, length);
return sum == number;
}
private int armstrongSum(int number, int length) {
int sum = 0;
if (number != 0) {
int digit = Math.floorMod(number, 10);
int powerRaised = (int) Math.pow(digit, length);
sum += powerRaised;
sum += armstrongSum(number / 10, length);
}
return sum;
}
public int lengthChecker(int number) {
int length = String.valueOf(number).length();
return length;
}
}
This is pretty common in recursion, where the parameters to the recursive part of the algorithm are a little different (usually there are more of them) than what you want a client of the API to have to pass in. The number changes in each recursive call, where number / 10 is passed down, but the same length is passed all the way through.
Notice that the recursive armstrongSum uses the return value from the recursive call, and that there is no need to create another instance of ArmstrongChecker when you are already in an instance method of the class.
I tried to create a code to take in a whole number in Java and output it in binary. The problem would seem that the binary is printing out backward. For instance, 6 should output as 011 but comes out as 110.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner in =new Scanner(System. in );
userNum = in.nextInt();
binary(userNum);
System.out.print("\n");
}
private static void binary(int userNum) {
int remainder;
while (userNum <= 1) {
System.out.print(userNum);
return;
}
remainder = userNum % 2;
binary(userNum >> 1);
System.out.print(remainder);
}
}
I tried incorporating a push stack to push the remainder into a stack that I can pull later, but couldn't quite get it to land.
private static void reverse(int userNum) {
String backwards;
while (userNum >= 0) {
backwards.push(int userNum);
System.out.println(backwards);
return;
}
}
It is part of a class assignment which asks the following.
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:
As long as x is greater than 0
Output x % 2 (remainder is either 0 or 1)
x = x / 2
Note: The above algorithm outputs the 0's and 1's in reverse order.
Ex: If the input is:
6
the output is:
011
6 in binary is 110; the algorithm outputs the bits in reverse.
These are the tests the program applies and my results.
Input 6
Your output binary is:110
Expected output 011
Input 19
Your output 10011
Expected output 11001
Input 255
Your output 11111111
Expected output 11111111
Any help or guidance in this, I would be greatly appreciative of it.
Per the requirement and not taking into consideration of negative numbers
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
while(userNum > 0){
System.out.print(userNum % 2);
userNum = userNum / 2;
}
System.out.print("\n");
}
}
First using predefined method then a custom one.
public class IntToBinary {
public static void main(String[] args) {
int decimalNumber = 10;
System.out.println(Integer.toBinaryString(decimalNumber));
System.out.println(convertBinary(10));
}
public static String convertBinary(int num) {
StringBuilder sb = new StringBuilder();
int binary[] = new int[40];
int index = 0;
while (num > 0) {
binary[index++] = num % 2;
num = num / 2;
}
for (int i = index - 1; i >= 0; i--) {
sb.append(binary[i]);
}
return sb.toString();
}
}
Your program appears to work fine for positive values. However it does not handle negative numbers which have their own unique binary representation known as two's complement. You could do something like the following to accommodate:
private static void binary(int userNum) {
int remainder;
// while (userNum <= 1) {
// System.out.print(userNum);
// return;
// }
if (userNum == 0) {
return;
}
// simply mask off the bit instead of dividing by two
remainder = userNum & 1;
// and shift right thru the sign bit
binary(userNum >>> 1);
System.out.print(remainder);
}
}
binary(-6));
prints
11111111111111111111111111111010
And the reason these printed out in proper order is because your routine is recursive. That is a natural behavior of printing the values stored in the stack from a recursive procedure.
import java.util.Scanner;
public class Reverse_BinaryNum {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
int inputNum;
System.out.println("Enter the Digit : ");
inputNum = scnr.nextInt();
System.out.println("The Reverse Binary for the given Digit is : ");
while (inputNum > 0) {
System.out.print(inputNum % 2);
inputNum = inputNum / 2;
}
scnr.close();
}
}
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);
}
Im having trouble converting binary to a decimal. We have to use a function for the conversion and do it by hand rather than use a predefined function. This is what I have so far, I know it is a mess but I am stuck on how to fix it. Thanks!
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (!"-1".equals(inString)) {
int i;
int binaryLength;
binaryLength = inString.length();
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
System.out.println(decimal);
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
To use a function, as your assignment requires, you have to write the function outside the main method, and then include a statement that calls the function. So move this above the line that says public static void main:
public static int binaryToDecimal (String binaryString) {
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, each function or method (including main) has its own variables that it uses, called local variables; but the local variables that each function uses are its own separate copies. Thus, the above function won't be able to use the binaryLength or decimal variabes belonging to main. You'll need to declare them inside binaryToDecimal:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1')
decimal = decimal + Math.pow(2,inString.length() - 1 - i);
}
return (int) decimal;
}
Also, this function won't be able to access main's inString, but the idea is that you've given the function the string you want to work with, which it refers to as binaryString. So change inString to binaryString in the function:
public static int binaryToDecimal (String binaryString) {
int decimal;
int binaryLength;
for (i = binaryLength - 1, decimal = 0; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal = decimal + Math.pow(2,binaryString.length() - 1 - i);
}
return (int) decimal;
}
And also note that the binaryLength and decimal variables are totally unrelated to the variables of the same name in main. That means that when you assigned binaryLength in main, that has no effect on binaryLength in binaryToDecimal. You'll need to assign it in the function. Change int binaryLength; to
int binaryLength = binaryString.length();
Finally, in order to use the function, main will need to call it. Put this in the main function:
decimal = binaryToDecimal(inString);
When main executes that, it will call the function and tell it to work with inString. The function will call that binaryString, though. The function will return a result, and then main will assign that result to the variable decimal--that means the local variable decimal that belongs to main, since the above statement is inside main.
I don't know if this will make your whole program work. (It should, but I'm not sure.) But I'm just trying to explain the details of how to use functions.
The confusing part is with the Math.pow, and its complicated arguments, where off-by-one errors are easily made.
Yet, if we have a number at base 10, like
123
its value is
(((0*10)+1)*10+2)*10+3
This looks complex, but note the easy pattern: Starting out with 0, we go through the digits. As long as we have another dgit, we multiply the previous result by the base and add the digit value. That's all! No Math.pow, no complex index calculations.
Hence:
String s = "1010";
int value = 0;
int base = 2;
for (i=0; i < s.length(); s++) {
char c = s.charAt(i);
value = value * base;
value = value + c - '0';
}
When I cleaned up your code, it worked just fine -
public static int binaryToDecimal(String binaryString) {
int binaryLength = binaryString.length();
int decimal = 0;
for (int i = binaryLength - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1') {
decimal += Math.pow(2, binaryLength - 1 - i);
}
}
return decimal;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String inString = input.nextLine();
while (!"-1".equals(inString)) {
System.out.println(binaryToDecimal(inString));
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
Output
Enter a binary number:
01
1
Enter a binary number:
10
2
Enter a binary number:
-1
All set !
Here's the function after a little clean up.
public static int binaryToDecimal (String binaryString) {
int decimal = 0;
int base = 2;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal += Math.pow(base,i);
}
return decimal;
}
I'm supposed to use a recursive method to print out the digits of a number vertically.
For example, if I were to key in 13749, the output would be:
1
3
7
4
9
How should I approach this question?? It also states that I should use the if/else method to check for the base case.. I just started learning java and I'm not really good at it :(
import java.util.Scanner;
public class test2 {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
System.out.println();
System.out.println(numbers(n));
}
public static int numbers(int n){
int sum;
if (n == 0) {
sum = 1;
} else {
System.out.println(n%10);
sum = numbers(n / 10) + (n % 10);
}
return sum;
}
}
Here is my code in C++
Just modify it for Java. You need to show the number after you call the function that way you show the last one first... as per the answer from s.ts
void recursive(int n) {
if (n < 10)
cout << n << endl;
else
{
recursive(n / 10);
cout << n % 10 << endl;
}
}
I was asked this question today in an interview!
public class Sandbox {
static void prints(int d) {
int rem = d % 10;
if (d == 0) {
return;
} else {
prints(d / 10);
}
System.out.println(rem);
}
public static void main(String[] args) {
prints(13749);
}
}
Output:
1
3
7
4
9
You asked how to approach this, so I'll give you a tip: it would be a lot easier to build up the stack and then start printing output. It also doesn't involve manipulating strings, which is a big plus in my book. The order of operations would be:
Check for base case and return if it is
Recursive call
Print
This way when you get to the base case, you'll start printing from the tail to the head of the calls:
recursive call 1
recursive call 2
recursive call 3
.... reached base case
print 3
print 2
print 1
This way you can simply print number % 10 and make the recursive call with number / 10, the base case would be when number is 0.
class PrintDigits {
public static void main(String[] args) {
String originalNumber, reverse = "";
// Creating an Scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter a number:");
// Reading an input
originalNumber = in.nextLine();
// Calculating a length
int length = originalNumber.length();
// Reverse a given number
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + originalNumber.charAt(i);
//System.out.println("Reverse number: "+reverse);
digits(Integer.parseInt(reverse));
}
/* digits of num */
public static void digits(int number) {
if (number == 0)
System.out.println("");
else {
int mode=10;
System.out.println(+number%mode);
digits(number/mode);
}
}
}
If number consists of more than one digit print ( n / 10 )
print ( n % 10 )
If you want them printed in the other order
print ( n % 10 )
If number consists of more than one digit print ( n / 10 )
try this
public class Digits {
public static void main(String[] args) {
printDigits(13749);
}
private static void printDigits(Integer number) {
int[] m = new int[number.toString().toCharArray().length];
digits(number, 0, m, 0);
for (int i= m.length - 1; i>=0; i--) {
System.out.println(m[i]);
}
}
public static int digits(int number, int reversenumber, int[] m, int i) {
if (number <= 0) {
return reversenumber;
}
m[i] = (number % 10);
reversenumber = reversenumber * 10 + (number % 10);
return digits(number/10, reversenumber, m, ++i);
}
}
Python example
def printNoVertically(number):
if number < 9:
print(number)
return
else:
printNoVertically(number/10)
print(number % 10)