ProgrammingNoob1234

Untitled

Jul 19th, 2020
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.53 KB | None | 0 0
  1. public class FewestOperationsToGetTo1 {
  2.     public static void main(String[] args) {
  3.         int n = 15;
  4.         System.out.println(operations(n));
  5.  
  6.     }
  7.  
  8.     private static int operations(int n) {
  9.         if (n == 0) {
  10.             return 1;
  11.         }
  12.         if (n == 1) {
  13.             return 0;
  14.         }
  15.         if (n % 2 == 0) {
  16.             return 1 + operations(n/2);
  17.         }
  18.         int first = 1 + operations(n - 1);
  19.         int second = 1 + operations(n + 1);
  20.         return Math.min(first, second);
  21.     }
  22. }
Advertisement
Add Comment
Please, Sign In to add comment