由1变成2,按红蓝按钮皆可,所以特殊处理1;
从A变成a,从B变成b,只要是偶数就是蓝色按钮的逆操作。(底数为2的对数复杂度,步数最少)
import java.util.*; public class Main { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int a = sc.nextInt(), b = sc.nextInt(); int A = sc.nextInt(), B = sc.nextInt(); StringBuilder button1 = new StringBuilder(""); //A变成a的按钮序列 while(A > 0 && A != a){ if(A%2 == 0){ button1.append('B'); A /= 2; }else{ button1.append('R'); A--; } } StringBuilder button2 = new StringBuilder(""); //B变成b的按钮序列 while(B > 0 && B != b){ if(B%2 == 0){ button2.append('B'); B /= 2; }else{ button2.append('R'); B--; } } if(button1.toString().equals(button2.toString())){ System.out.println(button1.length()); }else{ int n = button1.length(); int m = button2.length(); if((a == 1 || b == 1)&&button1.toString().substring(0, n - 1).equals(button2.toString().substring(0, m - 1))){ System.out.println(button1.length()); } else System.out.println(-1); } } }