几种方法的尾递归实现

http://freejvm.iteye.com/blog/976878

需要找时间验证一下,另外还需要学习多个参数的尾递归如何来实现的技巧

斐波那契数列第n个数的求值,

 public static long fibo4(int n)
        {
            if (n < 2)
            {
                return n - 1;
            }
            else
            {
                return fibo4Helper(n, 0, 1, 3); //保持与非尾递归接口不变,是借助帮助方法实现尾递归的    
            }
        }
        private static long fibo4Helper(int n, long prepre, long pre, int begin)
        {
            if (n == begin)
            {
                return pre + prepre;
            }
            else
            {
                return fibo4Helper(n, pre, prepre + pre, ++begin);    //这里相当于迭代实现for-loop的浓缩      
            }
        }   
//----------------------尾递归的其他实现-------------------------------------->  
    //2. 求最大公约数  
    public static int gcd(int big,int small){  
        if(big%small==0) return small;  
        return gcd(small, big%small);  
    }  
    //3.1 阶乘--非尾递归  
    public static int fn1(int n){  
        if(n<2) return 1;  
        return n*fn1(n-1);  
    }  
    //3.2 阶乘--尾递归  
    public static int fn2(int n){  
        if(n<2) return 1;  
        return fn2Helper(1, n);  
    }  
    private static int fn2Helper(int ret, int n){  
        if(n<2) return ret;  
        return fn2Helper(ret*n,n-1);  
    }  
        //4.1 翻转字符串--非尾递归  
       public static String reverse1(String s, int length){  
            if(length==0) return ""; //下一行的"+"可借助高版本JDK编译器的优化  
            return s.charAt(length-1)+reverse1(s,length-1);  
        }  
       //4.2 翻转字符串--尾递归  
       public static String reverse2(String s){  
           return reverse2Helper(s, "", s.length());  
       }  
       private static String reverse2Helper(String s,String init,int len){  
           if(len==0) return init;  
           return reverse2Helper(s, init+s.charAt(len-1), len-1);  
       }  
    //5. 验证字符串是否是回文 testHuiwen("abcdcba")  
     public static boolean testHuiwen(String s){  
         return testHuiwenHelper(s, 0, s.length());  
     }  
     private static boolean testHuiwenHelper(String s,int begin, int len){  
         if(begin< len>>1 && s.charAt(begin)==s.charAt(len-begin-1))   
             return testHuiwenHelper(s, begin+1, len);  
         else if(begin==len>>1) return true;  
         else return false;  
     }  
    //6. 翻转整数 如:1024=>4201  
     public static int reverseInt(int i){  
         return reverseIntHelper(i, 0);  
     }  
     private static int reverseIntHelper(int i, int init){  
         if(i==0) return init;  
         return reverseIntHelper(i/10, init*10+i%10);  
     }  
}  

 

你可能感兴趣的:(递归)