【算法刷题】Day6

1、月落乌啼算钱(斐波那契数列)

在这里插入图片描述
原题链接


很简单的斐波那契额数列
可以直接用公式算出来
也可以用迭代或者递归

public static void main2(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        double a = Math.sqrt(5);//开根号5
        double b = (Math.pow((1+a),n) - Math.pow((1-a),n)) / (Math.pow(2,n) * a);
        System.out.printf("%.2f",b);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        double a = 1.00;
        double b = 1.00;
        double Fn = 0.00;
        if (n == 0) {
            System.out.println(0);
        }
        if (n == 1) {
            System.out.println(a);
        }
        if (n == 2) {
            System.out.println(b);
        }
        if (n >= 3) {
            for (int i = 3; i <= n; i++) {
                Fn = a + b;
                a = b;
                b = Fn;
            }
            System.out.printf("%.2f",Fn);
        }
    }

2、P1307 [NOIP2011 普及组] 数字反转

在这里插入图片描述
原题链接


这道题看起来很简单
但是要考虑到正负号的问题
还有消去0的问题
我们这里用链表的方式来写

	public static void main17(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int flag = 1;
        List<Character> list = new ArrayList<>();
        String str = String.valueOf(n);
        if(n < 0){
            flag = -1;
            for (int i = str.length()-1; i > 0 ; i--) {
            //length() - 1 是因为有负号的存在
                if(str.charAt(i)=='0' && list.size()==0){
                    continue;
                }
                list.add(str.charAt(i));
            }
        }else{
            for (int i = str.length()-1; i >=0 ; i--) {
                if(str.charAt(i)=='0' && list.size()==0){
                    continue;
                }
                list.add(str.charAt(i));
            }
        }
        int count = list.size()-1;
        int ret =0;
        for (int i = 0; i < list.size(); i++) {
            ret += (list.get(i)-'0')* Math.pow(10,count--);
            //这里list.get(i)-'0' 是因为创建list用的是Character 类型 需要转化成int类型
        }
        System.out.println(ret*flag);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柒柒要开心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值