Reputation: 3
Need to write a method that returns the number of digits foe an integer number.
At first I did it using the iterative approach and everything worked just fine, however, when I want to edit the code using recursion I'm always stuck at the first counting and can't figure out why. Any help is much appreciated..
public static int numberLength(int n) {
if (n < 0) {
n *= (-1);
} else if (n == 0) {
return 1;
}
int digits = 0;
if (n > 0) {
digits += 1;
numberLength(n / 10);
}
return digits;
Upvotes: 0
Views: 8144
Reputation: 13
A possible solution could look like this:
public static int numberLength(int n){
if(n < 0){
return numberLength(-n);
}
else if(n == 0){
return 0;
}
else{
return 1 + numberLength(n/10);
}
}
public static void main(String[] args){
System.out.println(numberLength(-152555)); //returns 6
}
Upvotes: 0
Reputation: 678
In a recursive method you need to return some value based on reducing the size of the input value and combining this with your current count so far e.g.
public static int numberLength(int n){
if(n < 10){
return 1;
}
return 1 + (numberLength(n/10)); //This line combines the result
}
Upvotes: 2
Reputation: 45309
The problem is that you're discarding the result of numberLength(n / 10);
You probably meant to type:
int digits = 0;
if (n > 0) {
return 1 + numberLength(n / 10);
}
return digits;
Upvotes: 0