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.
Related
I am trying to find a way to identify 1 or 2 digit numbers in a string (there can't be any 3 digit numbers), add them together so they must be between 80 and 95.
For some reason, the code is not working, as it is always returning false, even when it should (in theory) return true.
ex. "Hi 57 how are you 30" returns false
Thank you in advance for your help!
("line" is the name of the String.)
public boolean isDig(){
int total=0;
int h;
int length = line.length();
for(h=0; h < length-1; h++) {
if (Character.isDigit(line.charAt(h))){
if (Character.isDigit(line.charAt(h+1))){
if (Character.isDigit(line.charAt(h+2))){
return false;
}
else {
total= total+(line.charAt(h)+line.charAt(h+1));
h++;
}
}
else {
total= total+(line.charAt(h));
}
}
if (total>=80 && total<=95){
return true;
}
else {
return false;
}
}
The main problem in the code is that line.charAt(h) isn't the numeric value of the digit at position h. It's the codepoint value, for example '0' is 48.
The easiest way to obtain the numeric value is Character.getNumericValue(line.charAt(h)), and similarly in other places.
You're also missing the multiplication by 10 of the first digit in the pair.
Assuming you know that the string is valid, it's easy enough just to add up any numbers in the string. The fact that they are 2 or 3 digits doesn't really matter from the perspective of obtaining the sum.
int total = 0;
for (int i = 0; i < line.length(); ) {
// Skip past non-digits.
while (i < line.length() && !Character.isDigit(line.charAt(i))) {
++i;
}
// Accumulate consecutive digits into a number.
int num = 0;
while (i < line.length() && Character.isDigit(line.charAt(i))) {
num = 10 * num + Character.getNumericValue(line.charAt(i));
}
// Add that number to the total.
total += num;
}
You should use a regex for this kind of parsing :
public class Example {
public static void main(String[] args) {
String input = "Hi 57 how are you 30";
System.out.println(process(input));
}
private static boolean process(String input) {
Pattern pattern = Pattern.compile(".*?(\\d+).*?(\\d+)");
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
int one = Integer.parseInt(matcher.group(1));
int other = Integer.parseInt(matcher.group(2));
System.out.println(one);
System.out.println(other);
int total = one + other;
return total >= 80 && total <= 95;
}
return false;
}
}
Output :
57
30
true
One of the possible solution it to use Regual Expression.
public static boolean isValid(String str) {
// regular expression matches 1 or 2 digit number
Matcher matcher = Pattern.compile("(?<!\\d)\\d{1,2}(?!\\d)").matcher(str);
int sum = 0;
// iterate over all found digits and sum it
while (matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
return sum >= 80 && sum <= 95;
}
Let a java.util.Scanner do the work:
public boolean scan(String line) {
Scanner scanner = new Scanner(line);
scanner.useDelimiter("\\D+");
int a = scanner.nextInt();
int b = scanner.nextInt();
int sum = a + b;
return sum >= 80 && sum <= 95;
}
The invocation of .useDelimiter("\\D+") delimits the string on a regular expression matching non-digit characters, so nextInt finds the next integer. You'll have to tweak it a bit if you want to pick up negative integers.
You could convert the String into an Array and test to see if each element in the String (separated by a space) is a Digit by testing the Integer.parseInt() method on each String element. Here is an example below:
public static boolean isDig(String theString) {
String[] theStringArray = theString.split(" ");
ArrayList<Integer> nums = new ArrayList<Integer>();
for(int x = 0; x < theStringArray.length; x++) {
String thisString = theStringArray[x];
try {
int num = Integer.parseInt(thisString);
nums.add(num);
}catch(NumberFormatException e) {
continue;
}
}
int total = 0;
for(int num: nums) {
total += num;
}
if(total >= 80 && total <= 95) {
return true;
}
else {
System.out.println(total);
return false;
}
}
We first split the original String into an Array based on the empty spaces. We then create an ArrayList that will add each digit in the String to it. We then create a for loop to look at each individual String in the Array and we set up a try-catch block. If we can covert the digit into an int using the Integer.parseInt() method, we will add it to the ArrayList. If not, we will catch the exception and continue the loop with a "continue" statement. Once we break out of the loop, we can create a variable called "total" and create another for loop in order to add each digit in the ArrayList to the total amount. If the total is greater than/equal to 80 and less than/equal to 95, we will return True, or else we will return false. Let's test the code:
String digitTest = "There is a digit here: 50 and a digit here 45";
System.out.println(isDig(digitTest));
The numbers 50 and 45 should equal 95 and our result is:
true
How to exit from a method, i.e how can i return from a function in this recursion in java?
public class solution {
public static int countZerosRec(int input){
int n=0;
int k =0;
int count=0;
//Base case
if(n==0)
{
return; // How can i return the method from here, i.e how can i stop the execution of the recursive program now.
}
k=input%10;
count++;
n=input/10;
countZerosRec(n);
int myans=count;
return myans;
}
}
Please help me getting out of this method.
This is a program to count number of zeroes.
Example, 34029030 ans = 3
You can try below approach:
public class MyClass {
public static void main(String args[]) {
System.out.println("total zeroes = " + returnZeroesCount(40300));
}
public static int returnZeroesCount(int input){
if(input == 0)
return 0;
int n = input % 10;
return n == 0 ? 1 + returnZeroesCount(input / 10) : returnZeroesCount(input / 10);
}
}
How it works: Assuming your input > 0, we try to get the last digit of the number by taking the modulus by 10. If it is equal to zero, we add one to the value that we will return. And what will be the value that we would be returning? It will be the number of zeroes present in the remaining number after taking out the last digit of input.
For example, in the below case, 40300: we take out 0 in first step, so we return 1+number of zeroes in 4030. Again, it appears as if we have called our recursive function for the input 4030 now. So, we again return 1+number of zeroes in 403.
In next step, since last number is 3, we simply return 0+total number of zeroes in 40 or simply as total number of zeroes present in 40 and so on.
For ending condition, we check if the input is itself 0. If it is zero then this means that we have exhausted the input number and there are no further numbers to check for. Hence, we return zero in that case. Hope this helps.
If your main focus is to find number of zeroes in a given number , You can use this alternatively:
int numOfZeroes =0;
long example = 670880930;
String zeroCounter = String.valueOf(example);
for(int i=0; i< example.length();i++){
if(zeroCounter.charAt(i) ==0){
numOfZeroes++;
}
}
System.out.print("Num of Zeros are"+ numOfZeroes);` `
Instead of posting a code answer to your question, I'll post a few pointers to get you moving.
As #jrahhali said, as your code is, it'll not get past the return
statement inside the if block(which is an error BTW, because you have an int return
type).
I'd recommend that you move the last two lines to some calling
function(such as a main method). That way all this function will
need to do is do some basic processing and move forward.
You aren't checking k at all. As it is, your count is going to
always increment.
Hope this much is enough for you to figure things out.
int count =0;
private int getZeroCount(int num){
if(num+"".length == 1){
if(num==0){
count++;
}
return count;
}
if(num%10 == 0){
count++;
}
num /= 10;
getZeroCount();
}
Method1 :
public static int countZero1(int input) {
int count = 0;
//The loop takes the remainder for the value of the input, and if it is divided by 10, then its number of digits is 0.
// When the value of the input is less than 0, the cycle ends
while (input >0){
if (input % 10 == 0){
count ++;
}
input /= 10;
}
return count;
}
Method2 :
private static int count = 0;
public static int countZero2(int input) {
//Recursive call function
if (input % 10 == 0){
count ++;
}
input /= 10;
if (input <= 0){
return count;
}else {
return countZero2(input);
}
}
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);
}
}
}
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;
}
}
I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
long addSquaresOfDigits(int number) {
long result = 0;
int tmp = 0;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);
Assuming the number is an integer to begin with:
int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;
for (int i = 0; i < strLength; ++i) {
int digit = Integer.parseInt(strNum.charAt(i));
sum += (digit * digit);
}
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
public static ArrayList<Integer> splitViaString(long number) {
ArrayList<Integer> result = new ArrayList<>();
String s = Long.toString(number);
for (int i = 0; i < s.length(); i++) {
result.add(s.charAt(i) - '0');
}
return result; // MSD at start of list
}
vs
public static ArrayList<Integer> splitViaModulo(long number) {
ArrayList<Integer> result = new ArrayList<>();
while (number > 0) {
int digit = (int) (number % 10);
result.add(digit);
number /= 10;
}
return result; // LSD at start of list
}
Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)
So not a lot in it really, but I was a bit surprised that String was faster
In the above example we can use:
int digit = Character.getNumericValue(strNum.charAt(i));
instead of
int digit = Integer.parseInt(strNum.charAt(i));
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
This code returns the first number (after 1) that fits your description.
public static void main(String[] args) {
int i=2;
// starting the search at 2, since 1 is also a happy number
while(true) {
int sum=0;
for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
int j=Character.getNumericValue(ch);
// getting the numeric value of the current char.
sum+=Math.pow(j, j);
// adding the current digit raised to the power of itself to the sum.
}
if(sum==i) {
// if the sum is equal to the initial number
// we have found a number that fits and exit.
System.out.println("found: "+i);
break;
}
// otherwise we keep on searching
i++;
}
}