|
| 1 | +/** |
| 2 | + * Created by 周杰伦 on 2018/3/10.650. 2 Keys Keyboard |
| 3 | + DescriptionHintsSubmissionsDiscussSolution |
| 4 | + Pick One |
| 5 | + Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: |
| 6 | +
|
| 7 | + Copy All: You can copy all the characters present on the notepad (partial copy is not allowed). |
| 8 | + Paste: You can paste the characters which are copied last time. |
| 9 | + Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'. |
| 10 | +
|
| 11 | + Example 1: |
| 12 | + Input: 3 |
| 13 | + Output: 3 |
| 14 | + Explanation: |
| 15 | + Intitally, we have one character 'A'. |
| 16 | + In step 1, we use Copy All operation. |
| 17 | + In step 2, we use Paste operation to get 'AA'. |
| 18 | + In step 3, we use Paste operation to get 'AAA'. |
| 19 | + Note: |
| 20 | + The n will be in the range [1, 1000]. |
| 21 | + */ |
| 22 | +public class KeysKeyboard { |
| 23 | + public int minSteps(int n) { |
| 24 | + if (n == 1) { |
| 25 | + return 0; |
| 26 | + } |
| 27 | + else if(n % 2 == 0) { |
| 28 | + return minSteps(n/2) + 2; |
| 29 | + } |
| 30 | + else if( !isPrime(n)) { |
| 31 | + return n; |
| 32 | + } |
| 33 | + else { |
| 34 | + double tmp = Math.sqrt(n); |
| 35 | + int min = 1000; |
| 36 | + for(int i= 2;i <=tmp; i++) { |
| 37 | + if (n % i == 0) { |
| 38 | + if(minSteps(n/i) + i < min ) { |
| 39 | + min = minSteps(n/i) + i; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + return min; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + boolean isPrime( int num ) |
| 48 | + { |
| 49 | + double tmp = Math.sqrt(num); |
| 50 | + for(int i= 2;i <=tmp; i++) { |
| 51 | + if (num % i == 0) { |
| 52 | + return true; |
| 53 | + } |
| 54 | + } |
| 55 | + return false ; |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String[] args) { |
| 59 | + |
| 60 | + } |
| 61 | +} |
0 commit comments