[LC 453]. Minimum Moves to Equal Array Elements

再写一个脑筋急转弯的题吧

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n – 1 elements by 1. Example: Input: [1,2,3], Output:3. [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]

给n-1个element-1就相当于给最大值+1…
所以move总数相当于把所有数字减到最小值需要的总步数…

res = sum – min * n

Advertisements

[LC 233] Number of Digit One

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

写一个我能看的懂的解题思路-_-

Go through each digit. Count the possible numbers under n if the current digit is 1.

例如一个数用abcdef表示,一共6位。假设现在已经scan到d的位置,这个数字可分割成三个部分(abc)d(ef)。有三种情况:

1 如果当前d是0。

例如(314)0(59)。若使d这一位为1,那么abc的位置可以取0-313, 一共314个选择。d是1。ef的位置可以取0-99所有可能,一共100个选择。加一起是abc * 100个可能的数字。

2 如果当前d是1.

例如(314)1(59)。若使d这一位为1,那么abc的位置可以取0-314,一共315个选择。d是1。ef的位置,当abc是0-313的时候,可以取0-99,当abc是314的时候,只能取0-59。所以加一起是abc * 100 + ef + 1个可能的数字。

3 如果当前d是>=2。

例如(314)2(59)。若使d这一位为1,那么abc的位置可以取0-314,一共315个选择。d是1。ef的位置可以取0-99,一共100个选择。加一起是(abc + 1)* 100

总结一下,对(abc)d(ef)
d == 0, count += abc * 100
d == 1, count += abc * 100 + ef + 1
d >= 2, count += abc * 100 + 100;

    public int countDigitOne(int n) {
        if (n <= 0) return 0;         
        int count = 0;         
        int x = 1;         
        int a = n;       
        while (a > 0) {
            int digit = a % 10;
            a /= 10;
            int b = n % x;
            if (digit == 0) count += a * x;
            else if (digit == 1) count += a * x + b + 1;                
            else count += (a + 1) * x;
            x *= 10;
        }
        return count;
    }

[LC 319]. Bulb Switcher

Brain teaser, just for fun.

There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it’s off or turning off if it’s on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

A bulb is turned on, if and only if its number has odd numbers of factors. For example:

bulb no.: 1,2,3,4,5,6,7,8,9,10
#factors: 1,2,2,3,2,4,2,4,3,4

Factors come in pairs. For example: for 6, 1 and 6, 2 and 3 are its factors. Only square numbers have odd numbers of factors, because they have a pair of the same factors. For example: for 4, 1 and 4, 2 and 2 are its factors. So the problem reduces to count the number of square numbers below n.

The square numbers below n have the property: i^2 <= n, where i is the count we want to know. So, i <= sqrt(n).

The result/count = (int)Math.sqrt(n).