zoukankan      html  css  js  c++  java
  • 整数变换问题:

    整数i的两种变换定义为,(向下取整);设计一个算法求给定两个整数ab,用最少次数的变换将整数a变换为b;例如

    import java.util.*;
    public class IntTransform{
    static int m;
    static int tempcount,bestcount;//当前变换次数,最少次数
    static int[] temp1=new int[100];
    static int[] temp2=new int[100];
    public static void main(String args[]){
    Scanner input=new Scanner(System.in);
    int n=input.nextInt();
    m=input.nextInt();
    tempcount=0;
    bestcount=100;
    Transform(n);
    System.out.println(bestcount);
    for(int i=bestcount;i>=1;i--){
    if(temp2[i]==2)System.out.print("f");
    if(temp2[i]==1)System.out.print("g");
    }
    }
    
    public static void Transform(int t){
    if(t==m){//找到转换方法
    if(tempcount<bestcount){
    bestcount=tempcount;//将最小转换次数赋值给bestcount
    for(int i=1;i<=bestcount;i++){
    temp2[i]=temp1[i];//temp2存最小次数转换方法
    }
    }
    return ;
    }
    
    int temp=t/2;
    tempcount++;
    if(tempcount<bestcount&& t>0){
    temp1[tempcount]=1;
    Transform(temp);
    }
    tempcount--;//回溯
        
    temp=3*t;
    tempcount++;
    if(tempcount<bestcount){
    temp1[tempcount]=2;
    Transform(temp);
    }
    tempcount--;//回溯
    }
    }

  • 相关阅读:
    Git配置
    第一次作业
    第二次作业
    python目前最好用的IDE——pycharm
    九九乘法表
    python语言的优点和缺点
    Python高效编程的19个技巧
    Python中 filter | map | reduce | lambda的用法
    Python 代码优化常见技巧
    求逆序对
  • 原文地址:https://www.cnblogs.com/ljs-666/p/7944878.html
Copyright © 2011-2022 走看看