【算法】程序猿不写代码是不对的73

本文介绍了一个算法问题:从0开始通过乘2或加1的操作达到目标整数n所需的最少步骤。采用动态规划方法实现,记录每个数值转换所需的最少操作次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.kingdz.algorithm.time201706;

import java.util.Arrays;

/**
 * <pre>
 * 步骤问题
 * 
 * http://judgecode.com/problems/1006
 * 
 * Suppose you start from x = 0.
 * In each step you can operate on x by either of the 2 operations:
 * (1) x = x * 2
 * (2) x = x + 1
 * Given an integer n. How many operations at least to change x into n?
 * 
 * Input:A single non-negative integer n which is no larger than 2147483647.
 * Output:The minimum number of operations to change x = 0 into n.
 * </pre>
 * 
 * @author kingdz
 * 
 */
public class Algo22 {

    public static void main(String[] args) {
        int n = 100;

        int[] arr = new int[n + 1];
        arr[0] = 1;
        for (int i = 0; i < arr.length; i++) {
            int now = arr[i];
            int a = i * 2;
            int b = i + 1;

            if (a < arr.length && arr[a] == 0) {
                arr[a] = now + 1;
            }

            if (b < arr.length && arr[b] == 0) {
                arr[b] = now + 1;
            }

            if (a == n || b == n) {
                break;
            }
        }
        System.out.println(arr[n] - 1);

        System.out.println(Arrays.toString(arr));
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值