题目

image.png

解题思路

解题代码

递归

  1. class Solution {
  2. public int integerReplacement(int n) {
  3. if(n == 1) return 0;
  4. if(n == Integer.MAX_VALUE) return 32;
  5. if((n & 1 ) == 0) return integerReplacement(n >> 1) + 1;
  6. else return Math.min(integerReplacement(n+1),integerReplacement(n-1) ) + 1;
  7. }
  8. }

递归(map减枝)

  1. class Solution {
  2. Map<Integer,Integer> map = new HashMap<>();
  3. public int integerReplacement(int n) {
  4. if(n == 1) return 0;
  5. if(n == Integer.MAX_VALUE) return 32; //避免溢出
  6. if(map.containsKey(n) ) return map.get(n);
  7. if((n & 1 ) == 0) { //炫技 模2可用 & 替换
  8. int cnt = integerReplacement(n >> 1) + 1; //炫技,除2可用>>替换
  9. map.put(n,cnt);
  10. return cnt;
  11. }
  12. else {
  13. int cnt = Math.min(integerReplacement(n+1),integerReplacement(n-1) ) + 1;
  14. map.put(n,cnt);
  15. return cnt;
  16. }
  17. }
  18. }

贪心

  1. class Solution {
  2. public int integerReplacement(int n) {
  3. if(n == 1) return 0;
  4. if(n == Integer.MAX_VALUE) return 32; //避免溢出
  5. int time = 0;
  6. while(n != 1) {
  7. if((n & 1 ) == 0) { // 为偶数
  8. n = n >> 1; //除2
  9. } else {
  10. n = n - 1; //默认-1
  11. //判断减1后,n除2后的奇偶性,若为基数且减1后的n不为2时取 n+ 2
  12. //需考虑特殊情况,n为3,减去1后,除2位1,不应取 原 n + 1
  13. if( ( ( n >> 1 ) & 1 ) == 1 && n != 2 ) {
  14. n = n + 2; //前面n - 1,故此处+2 (等价于 未减1的n 加 1)
  15. }
  16. }
  17. time++;
  18. }
  19. return time;
  20. }
  21. }