zoukankan      html  css  js  c++  java
  • 258. Add Digits

    题目:

    Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

    For example:

    Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

    Follow up:
    Could you do it without any loop/recursion in O(1) runtime?

    Hint:

      1. A naive implementation of the above process is trivial. Could you come up with other methods?
      2. What are all the possible results?
      3. How do they occur, periodically or randomly?
      4. You may find this Wikipedia article useful.

    链接: http://leetcode.com/problems/add-digits/

    3/4/2017

    不看别人答案绝对做不出来题目中不用循环的要求。

    自己的版本:

     1 public class Solution {
     2     public int addDigits(int num) {
     3         if (num < 10) return num;
     4 
     5         int sum = 10;
     6         while (sum >= 10) {
     7             sum = 0;
     8             while (num != 0) {
     9                 sum += num % 10;
    10                 num /= 10;
    11             }
    12             num = sum;
    13         }
    14         return sum;
    15     }
    16 }

    看别人答案:

    1.  (a + b) mod n  = ((a mod n) + (b mod n)) mod n

    2.  (a * b) mod n = ((a mod n) * (b mod n)) mod n

    1 public class Solution {
    2     public int addDigits(int num) {
    3         return 1 + (num - 1) % 9;
    4     }
    5 }

    我觉得这种题没见过就基本不要想按照那个要求来做了,有幸刷到就做,没刷到就爱谁谁。

  • 相关阅读:
    利用pipe实现进程通信一例
    司机和售票员问题 信号signal注册一例
    HDU 1003
    HDU 1847
    HDU 1846(巴什博弈)
    《断弦》感想
    夺冠概率
    熄灯问题
    HDU 2176(Nim博弈)
    NYOJ 541
  • 原文地址:https://www.cnblogs.com/panini/p/6504897.html
Copyright © 2011-2022 走看看