zoukankan      html  css  js  c++  java
  • Math Start!

    (1)Add Digits

    解题思路:

    基于同余的数学属性。 数字的根(即题目所要求返回的最终结果)与该数字除以9时的余数相同(并且该余数将始终为单个数字)。

    take 438 as an example

    [Step 1]:

    438  == 40*10 +3*10 +8 ;
    
    4+3+8 == 4*(10%9)*(10%9)+3*(10%9)+8%9= 15   ;
    

    [Step 2]:

    15  == 1*10 + 5 ;
     
    1+5 == 1*(10%9)+5%9= 6 ;
    

    [So we can see]:

    ab%9%9%9==ab%9; 
    
    just return num%9; and don't forget num==0 or num==9   

    代码如下:

    1 public class Solution {
    2     public int addDigits(int num) {
    3         return  num == 0 ? 0 : (num%9 == 0 ? 9 : (num%9));
    4     }
    5 }
    View Code

    (2)Minimum Moves to Equal Array Elements

    解题思路:

    实现使数组中的元素相等的目标,将1添加到n-1个元素与从一个元素中减去1相同。因此,最好的方法是使数组中的所有元素等于min元素。sum(array) - n * minimum

    代码如下:

     1 public class Solution {
     2     public int minMoves(int[] nums) {
     3         if (nums.length == 0) {
     4             return 0;
     5         }
     6         int min = nums[0];
     7         int sum = 0;
     8         for (int n : nums) {
     9             min = Math.min(n, min);
    10             sum += n;
    11         }
    12         return sum - nums.length*min;
    13     }
    14 }
    View Code

    (3)Excel Sheet Column Title

    解题思路:

    实质就是把10进制的数转换成26进制。

    代码如下:

    1 public class Solution {
    2     public String convertToTitle(int n) {
    3         return n == 0 ? "" : convertToTitle(--n / 26) + (char)('A' + (n % 26));
    4         //return n == 0 ? "" : convertToTitle((n - 1) / 26) + (char)('A' + ((n - 1) % 26));
    5     }
    6 }
    View Code
  • 相关阅读:
    计算机网络基础 汇总
    指针与数组
    卡特兰数
    Leetcode Sort Colors
    Leetcode Group Shifted Strings
    Leetcode Summary Ranges
    Leetcode Count Primes
    Leetcode Reverse Words in a String II
    Leetcode Reverse Words in a String
    Leetcode Rotate Array
  • 原文地址:https://www.cnblogs.com/struggleli/p/6196543.html
Copyright © 2011-2022 走看看