I tried to write a simple java program which counts how many odd digits there are inside a number (for example, for input "123" the program should return 2). The program instead returns all the digits of the given number. Any idea?
import java.util.*;
//Counts the number of odd digits in an int using recursion
public class OddCount{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
System.out.println("The number of odd digits is " + oddDigitCounter(n));
}
public static int oddDigitCounter(int number) {
int result = 0;
if(number<=10){
if(number%2==0)
result = 0;
else
result++;
}
else{
if(number%10!=0){
if((number%10)/2!=0)
result = 1 + oddDigitCounter(number/10);
else
result = 0 + oddDigitCounter(number/10);
}
else{
result = 0 + oddDigitCounter(number/10);
}
}
return result;
}
}
Here is a way to write your recursive method without all the unnecessary conditions.
public static int oddDigitCounter(int number) {
if (number==0) {
return 0;
}
return (number&1) + oddDigitCounter(number/10);
}
Using &1 instead of %2 allows it to work for negative numbers as well as positive ones.1
1 (number&1) is zero for an even number, and one for an odd number, and works regardless of whether the number is positive or negative. For instance, if number==-3 then (number%2)==-1, but (number&1)==1, which is what we want in this case.
Check your code, you are using / instead of % in this if condition:
if((number%10)/2!=0)
It should be:
if((number%10)%2!=0)
In oddDigitCounter() why don't you simply check digit by digit if it's an even or odd one and echo (store) the result?
Recursive approach: at first call you may pass to the function the entire number and then if the number is 1 digit long let the function do the check and return, otherwhise do the check against the 1st digit and pass the others again to the function itself.
Procedural approach: do a simple loop through the digits and do the checks.
You can use following sample:
import java.util.Scanner;
public class NumberOfOddDigist {
private static int count = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
countOdd(n);
System.out.println("The number of odd digits is " + count);
in.close();
}
public static void countOdd(int number) {
int remainder = number % 10;
int quotient = (number - remainder) / 10;
if (!(remainder % 2 == 0)) {
count++;
}
number = quotient;
if (number < 10) {
if (!(number % 2 == 0)) {
count++;
}
} else {
countOdd(number);
}
}
}
Related
*hi there here is my answer for this challenge :
Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
my code works and outputs a true value only if the number is a happy one*
public class Main {
public static void main(String[] args) {
System.out.println(isHappy(12));
}
public static boolean isHappy(int number) {
while (number != 1 ) {
number = SumOfintegers(number); //to keep looping until It find sum=1
}
return true ;
}
public static int SumOfintegers(int number){
int sum =0;
int news = 0;
while (number > 0) {
int num = number % 10;
number /= 10;
news = num * num;
sum = sum + news;
}
return sum;
}
}
so I have solved this "happy number" problem once and this is my code using recursion with explanation:
public static void main(String[] args) {
System.out.println(nextHappyNum(0));
}
//method to find next happy number
static int nextHappyNum(int num){
int x =num+1;
if(isHappy(x) == true){ //base case where the next number is happy number
return x;
} else{
return nextHappyNum(num+1); //recursively call the method to check
}
}
//method to check if number is happy or not
static boolean isHappy(int num){
while(num != 1 && num != 4){
num = calculateHappy(num); //this loop will call the checkHappy() method until it reach 1 or 4
}
if(num == 1){ //if result is 1 -> happy number
return true;
} else if(num == 4 ){ //final result is 4 -> not happy number
return false;
} else{
return false;
}
}
//method to calculate the sum of number digits
static int calculateHappy(int num){
int sum = 0;
int rem = 0;
//create while loop to calculate the digit number, remainder of modulus 10 is the second digit
//first digit is = the number/10 and the remainder of that int
while(num != 0){
rem = num%10; //calculating the remainder
sum += (rem*rem); //calculate the square root of remainder and add it to the sum
num = num/10; //divide the number by 10 - due to this data type is int, so the first digit will be taken
}
return sum;
}
When the for loop detects a number that is less than the positive integer inputted by the user and perfectly divisible, it prints it and that is because the for loop just continues counting through each number. However, I need it to prime factorize the positive integer inputted by the user.
import java.util.Scanner;
public class PrimeFactor {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int Number = console.nextInt();
for (int counter =2; counter < Number; counter++) {
if (Number % counter == 0) {
System.out.print(" "+counter);
}
}
}
}
What you need to do to print all factors is to divide Number by counter when you've determined that counter is a factor. You also need to try counter again, in case there is more than one copy of a factor in a number, e.g. 12 is 2 * 2 * 3. Don't forget to print whatever Number is at the end, in case it didn't drop all the way to 1.
for (int counter = 2; counter <= Math.sqrt(Number); counter++) {
while (Number % counter == 0) {
Number /= counter;
System.out.print(" " + counter);
}
}
// Print what's left.
if (Number > 1) {
System.out.println(" " + Number);
}
As an aside, I've also changed the for loop condition to stop at the square root of Number, because for prime factor trials, if you've found a factor greater than the square root, then you should have found the corresponding factor that is less than the square root first.
Additionally, normal Java naming conventions would have you name the variable number in lowercase, to avoid confusion with classes such as java.lang.Number.
Your on the right track you just need to divide Number (num in the below code) by counter in the loop:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = console.nextInt();
console.close();
System.out.printf("Prime factors of %d: %s%n", num, getPrimeFactors(num));
}
public static List<Integer> getPrimeFactors(int num) {
List<Integer> primeFactors = new ArrayList<>();
for (int counter = 2; counter <= num; counter++) {
while (num % counter == 0) {
primeFactors.add(counter);
num /= counter;
}
}
if (num > 1) primeFactors.add(num);
return primeFactors;
}
}
Example Usage:
Enter a positive integer: 12
Prime factors of 12: [2, 2, 3]
Using recursion I need to input a number and the console will print this number without its highest digit. If it's smaller than 10 it will return 0.
I already found the biggest digit but how can i remove it and print the number without it after?
This is the code for the biggest digit:
public static int remLastDigit(int n){
if(n==0)
return 0;
return Math.max(n%10, remLastDigit(n/10));
}
If i input 12345 i expect the output to be 1234. if i input 9 or less i expect the output to be 0.
Here is my solution:
// call this method
public static int removeLastDigit(int number) {
return removeLastDigitImpl(number, largestDigit(number));
}
private static int removeLastDigitImpl(int number, int largestDigit) {
if (number < 10) { // if the number is a single digit, decide what to do with it
if (number == largestDigit) {
return 0; // if it is the largest digit, remove it
} else {
return number; // if it is not, keep it
}
}
// handle the last digit of the number otherwise
if (number % 10 == largestDigit) {
// removing the digit
return removeLastDigitImpl(number / 10, largestDigit);
} else {
// not removing the digit
return removeLastDigitImpl(number / 10, largestDigit) * 10 + number % 10;
}
}
// this is the same as your attempt
private static int largestDigit(int n){
if(n==0)
return 0;
return Math.max(n%10, largestDigit(n/10));
}
Since you've already found the max digit nicely, here's how you can print the number without it.
public static void main(String[] args) {
printWithoutDigit(2349345, remLastDigit(2349345));
}
public static void printWithoutDigit(int number, int maxDigit) {
Integer.toString(number).chars().filter(digit -> Integer.valueOf(String.valueOf((char)digit))!=maxDigit).forEach(d -> System.out.print((char)d));
}
You could convert your number to a String, or more precisely to a char-array. Then, you can find out where in this array the biggest digit is, remove it and convert your char-array back to an integer.
This would roughly look like this:
int num = 12345; //the number from which you want to remove the biggest digit
char[] numC = String.valueOf(num).toCharArray();
int biggestDigit = 0;
int biggestDigitIndex = 0;
for (int i = 0; i < numC.length; i++) {
if (biggestDigit < Character.getNumericValue(numC[i])) {
biggestDigit = Character.getNumericValue(numC[i]);
biggestDigitIndex = i;
}
//Remove digit at index biggestDigitIndex from numC
//Convert numC back to int
}
Of course, you have to incorporate this into your recursion, which means returning the number you got after converting numC back to int and then feed this into your input parameter again. Also, of course you need to add a check if your number is < 9 in the beginning.
Hi very first Java class and it seems to be going a mile a minute. We learn the basics on a topic and we are asked to produce code for more advanced programs than what helped us get introduced to the topic.
Write a recursive program which takes an integer number as Input. The program takes each digit in the number and add them all together, repeating with the new sum until the result is a single digit.
Your Output should look like exactly this :
################### output example 1
Enter a number : 96374
I am calculating.....
Step 1 : 9 + 6 + 3 + 7 + 4 = 29
Step 2 : 2 + 9 = 11
Step 3 : 1 + 1 =2
Finally Single digit in 3 steps !!!!!
Your answer is 2.
I understand the math java uses to produce the output I want. I can do that much after learning the basics on recursion. But with just setting up the layout and format of the code I am lost. I get errors that make sense but have trouble correcting with my inexperience.
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println(n);
}
public int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
}
The output understandably duplicates the code given by the input from the user.
I had trouble calling the second class when I tried to split it up into two. I also know I am not soprln n, or the sum. So I try to make it into one and I can visibly see the problem but am unaware how to find the solution.
Think of recursion as solving a problem by breaking it into similar problems which are smaller. You also need to have a case where the problem is so small that the solution is obvious, or at least easily computed. For example, with your exercise to sum the digits of a number, you need to add the ones digit to the sum of all the other digits. Notice that sum of all the other digits describes a smaller version of the same problem. In this case, the smallest problem will be one with only a single digit.
What this all means, is that you need to write a method sumDigits(int num) that takes the ones digit of num and adds it to the sum of the other digits by recursively calling sumDigits() with a smaller number.
This is how you need to do : basically you are not using any recursion in your code. Recursion is basically function calling itself. Don't be daunted by the language, you will going to enjoy problem solving once you start doing it regularly.
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
printSingleDightSum(n);
}
public static void printSingleDightSum(int N) {
int sum = 0;
int num = N;
while(num !=0 ){
int a = num%10;
sum + = a;
num = num/10;
}
if(sum < 10) {
System.out.println('single digit sum is '+sum);
return;
} else {
printSingleDightSum(sum);
}
}
Here is the code, I will add comments and an explanation later but for now here is the code:
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.println("################### output example 1");
System.out.print("Enter number: ");
final int n = new Scanner(System.in).nextInt();
System.out.print("\nI am Calculating.....");
sumSums(n, 1);
}
public static int sumSums(int n, int step) {
System.out.print("\n\nStep " + step + " : ");
final int num = sumDigit(n);
System.out.print("= " + num);
if(num > 9) {
sumSums(num, step+1);
}
return num;
}
public static int sumDigit(int n) {
int modulo = n % 10;
if(n == 0) return 0;
final int num = sumDigit(n / 10);
if(n / 10 != 0)
System.out.print("+ " + modulo + " ");
else
System.out.print(modulo + " ");
return modulo + num;
}
}
I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.
My first attempt:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
int tempRev = RevDigs(input/10);
if(tempRev >= 10)
reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;
if(tempRev <10 && tempRev >0)
reverse = input%10*10 + tempRev;
if(tempRev == 0)
reverse = input%10;
return reverse;
}//======================
I also tried to use this, but it seems to mess up middle digits:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
if(RevDigs(input/10) == 0)
reverse = input % 10;
else
{
if(RevDigs(input/10) < 10)
reverse = (input % 10) *10 + RevDigs(input/10);
else
reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);
}
return reverse;
}
I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.
How about using two methods
public static long reverse(long n) {
return reverse(n, 0);
}
private static long reverse(long n, long m) {
return n == 0 ? m : reverse(n / 10, m * 10 + n % 10);
}
public static void main(String... ignored) {
System.out.println(reverse(123456789));
}
prints
987654321
What about:
public int RevDigs(int input) {
if(input < 10) {
return input;
}
else {
return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
/* here we:
- take last digit of input
- multiply by an adequate power of ten
(to set this digit in a "right place" of result)
- add input without last digit, reversed
*/
}
}
This assumes input >= 0, of course.
The key to using recursion is to notice that the problem you're trying to solve contains a smaller instance of the same problem. Here, if you're trying to reverse the number 13579, you might notice that you can make it a smaller problem by reversing 3579 (the same problem but smaller), multiplying the result by 10, and adding 1 (the digit you took off). Or you could reverse the number 1357 (recursively), giving 7531, then add 9 * (some power of 10) to the result. The first tricky thing is that you have to know when to stop (when you have a 1-digit number). The second thing is that for this problem, you'll have to figure out how many digits the number is so that you can get the power of 10 right. You could use Math.log10, or you could use a loop where you start with 1 and multiply by 10 until it's greater than your number.
package Test;
public class Recursive {
int i=1;
int multiple=10;
int reqnum=0;
public int recur(int no){
int reminder, revno;
if (no/10==0) {reqnum=no;
System.out.println(" reqnum "+reqnum);
return reqnum;}
reminder=no%10;
//multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
i++;
no=recur(no/10);
reqnum=reqnum+(reminder*multiple);
multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
return reqnum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=123456789;
Recursive r= new Recursive();
System.out.println(r.recur(num));
}
}
Try this:
import java.io.*;
public class ReversalOfNumber {
public static int sum =0;
public static void main(String args []) throws IOException
{
System.out.println("Enter a number to get Reverse & Press Enter Button");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
int number = Integer.parseInt(input);
int revNumber = reverse(number);
System.out.println("Reverse of "+number+" is: "+revNumber);
}
public static int reverse(int n)
{
int unit;
if (n>0)
{
unit = n % 10;
sum= (sum*10)+unit;
n=n/10;
reverse(n);
}
return sum;
}
}