c++ - 以最少的步骤将给定整数转换为另一个整数

标签 c++ algorithm pseudocode

给定两个位数相同的数字 A 和 B。通过在每个步骤中增加或减少 A 中的单个数字,找到将 A 转换为 B 的最少步骤数。
例如:如果 A = 133 和 B = 343,可能的解决方案是 133 -> 233 -> 333 -> 343。所需的最少步数为 3。

我尝试了一种蛮力方法。这是我的伪代码

  while(a!=b)
  {
   if(a<b)
      {
        find (b-a)
        count number of digits in (b-a) keep it as n
        add the power(10,n) to a
        moves++;
       }
     else{
       find (a-b)
        count number of digits in (a-b) keep it as n
        subtract the power(10,n) from a
        moves++;
        }

  }

我无法获得所有测试用例的正确答案。请提出一个有效的方法来做到这一点。

最佳答案

你的问题的解决方案是

  1. 逐位遍历a和b,差的绝对值加到一个变量sum
  2. sum 表示需要更改的位数
  3. 时间复杂度O(位数)

function solve(a, b){
    let sum = 0;
    while(a>0 && b>0){
        sum += Math.abs((a%10)-(b%10));
        a = Math.floor(a/10);
        b= Math.floor(b/10);
    }
    return sum;
}

console.log(solve(133, 343));
console.log(solve(1234, 1221));

关于c++ - 以最少的步骤将给定整数转换为另一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913026/

相关文章:

c++ - 在 C++ 或 Arduino 中,如何在函数中接受未知类型的参数?

java - 查找字符串中的所有回文

c++ - 使用 C++ 实现 Soundex 算法

python - 模式识别一维数据

algorithm - 不使用循环对字符串列表进行排序的伪代码

c++ - 库 (.tlb) 文件中宏的范围?

c++ - C 中的多维数组

java - 如何编写排列的递归算法?

c++ - 排序 32 位整数与排序 64 位整数一样快

algorithm - 将伪代码表示为 n 的函数