650. 2 Keys Keyboard

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:

  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
  2. Paste: You can paste the characters which are copied last time.

只能使用1.复制全部 2. 粘贴 两种操作,复制得一定长度字符串。求最小步数。

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'.
Example 1:

Input: 3
Output: 3
Explanation:
Initially, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.

Note:
The n will be in the range [1, 1000].


这题不是DP, 用数学解法就行。

class Solution {
    public int minSteps(int n) {
        int res = 0;
        while(n>1){
            int d = findDivider(n);
            res += d;
            n /= d;
        }
        return res;
    }
    public int findDivider(int n){
        for(int d=2;d<=Math.sqrt(n);d++){
            if(n%d==0) return d;
        }
        return n;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 人生绝不是轻松到你只要随便想想就可以应付,也绝不是沉重到要你日日苦不堪言;而是要明确自己的兴趣和梦想,然后义无反顾...
    d9894a518664阅读 200评论 0 0
  • 早上散步的时候,我的脑子里冒出一个问题。 这个问题很可笑,是一个假如。假如,在距离我很近的地方,有一堆钱...
    秦占勇阅读 241评论 2 4
  • 对于大学的我来说,即将12月了,意味着一个学期又快结束了。 很奇怪的现象,念了大学后,每学期的末尾,我们总...
    豆奶包wv阅读 188评论 0 0
  • 莱普瑞暖气中心距1730,宽度58 因空调位置变更,厨房的打眼位置。 测量卫生间浴帘和浴杆的高度,带卷尺,记号笔 ...
    泳池小胖鱼阅读 278评论 0 0