简体   繁体   中英

return statement is giving unexpected result during implementation of the method to find power of ten

I was solving the question where we are given a integer and we have to return the greatest power of 10 which is smaller than or equal to the value of given int n. i tried to solve it but the run time is not as expected.

  public int powerofTen(int n){
    int x;
    if(n>0){
    x =  1 + powerofTen(n/10);
    }else{
    return 0;
    }
    return x;
    }

if i replace last return x , statement with return (int)Math.pow(10,x-1) to get the correct answer the value displayed is 0. moreover if i try to use return x-1 instead of int x than too it shows 0.

a output for clearance: if n = 100

with return x value is 3.

with return x-1 value is 0.

with return (int)Math.pow(10,x-1) the value is 0.

This does not have to do with recursion at all, the error is not in recursion code. The problem is that you need your function return eg:

For input 100 the number 3 and probably return (int)Math.pow(10,x-1) . If you replace return x with (int)Math.pow(10,x-1) then you will have wrong result in the recursion calls. For example you will call the function with input 100 which will call the function with input 10 and so on, but you expect the call of the function with input 10 to return to the outer call the value 1. If you place return x-1 (or (int)Math.pow(10,x-1) ) instead of return x then you will take result 0 instead of 1 in the recursion for input 10 and so you will get also 0 for input 100.

The error is logical, in order to solve the problem you need to find the exponent eg for input 100 the number 3 and then return (outside from the function) (int)Math.pow(10,x-1) .

Even though it's already been replied, this way it's easier to see the steps to do in recursive algortihms:

  1. base case: any number less than 10 returns 0 as greatest exponent for 10

  2. recursive task: add 1 to the greatest exponent found for n/10

Some code:

public int powerofTen(int n){
    if(n<10)
        return 1;
    else
        return 10*powerofTen(n/10);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM