码迷,mamicode.com
首页 > 其他好文 > 详细

面试46.把数字翻译成字符串

时间:2020-06-10 21:23:26      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:tran   动态   src   bst   leetcode   class   lang   https   inf   

技术图片
技术图片

动态规划

思路

原文

技术图片
技术图片

代码

public int translateNum(int num) {
       String s=String.valueOf(num);
       int a=1,b=1;
       for(int i=2;i<=s.length();i++){
           String tmp=s.substring(i-2,i);
           int c=tmp.compareTo("10")>=0&&tmp.compareTo("25")<=0?a+b:a;
           b=a;
           a=c;
       }
       return a;
    }

优化

public int translateNum2(int num){
    int a=1,b=1,x,y=num%10;
    //从右往左
    while(num!=0){
        num/=10;
        x=num%10;
        int tmp=x*10+y;
        int c=(tmp>=10&&tmp<=25)?a+b:a;
        b=a;
        a=c;
        y=x;
    }
    return a;
}

参考链接

Krahets:动态规划,清晰图解

面试46.把数字翻译成字符串

标签:tran   动态   src   bst   leetcode   class   lang   https   inf   

原文地址:https://www.cnblogs.com/yh-simon/p/13088405.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!