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 }

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

  • 相关阅读:
    proguard-rules.pro、混淆、导jar包
    百度地图相关开发
    开发apicloud模块遇到的几个梗
    Android相关概念
    file-downloader相关问题
    Android 线程
    Android Studio Tip of the Day
    NAudio的使用说明
    IT回忆录-2
    IT回忆录-1
  • 原文地址:https://www.cnblogs.com/panini/p/6504897.html
Copyright © 2011-2022 走看看