• Leetcode 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?

    You may find this Wikipedia article useful.


    java code(3 methods)

     1 public class AddDigits {
     2     public static void main(String[] args) {
     3         //int x = 2048;
     4         System.out.println("in  out");
     5         for (int i = 0; i<= 29; i++) {
     6             int result = addDigits(i);
     7             System.out.printf("%2d  %2d", i, result);
     8             System.out.println();
     9         }
    10     }
    11 
    12     /*
    13     * method 1
    14     * run time: 344ms  slow
    15     * */
    16     public static int addDigits(int num) {
    17         int sum = 0;
    18         if( num < 10) {
    19             return num;
    20         }
    21         while(num >=10) {
    22             sum += num%10;
    23             num /= 10;
    24         }
    25         sum += num;
    26         return addDigits(sum);
    27     }
    28 
    29     /*
    30     * method 2
    31     * run time: 276ms  medium
    32     * */
    33     public static int addDigits(int num) {
    34         while (num / 10 > 0) {
    35             int sum = 0;
    36             while (num > 0) {
    37                 sum += num % 10;
    38                 num /= 10;
    39             }
    40             num = sum;
    41         }
    42         return num;
    43     }
    44 
    45     /*
    46     * method 3
    47     * run time: 240ms  fast!!
    48     * */
    49     public static int addDigits(int num) {
    50          return (num -1) % 9 +1;
    51     }

    Reference:

    1. http://bookshadow.com/weblog/2015/08/16/leetcode-add-digits/

    2. http://www.cnblogs.com/grandyang/p/4741028.html

  • 相关阅读:
    优化网站设计系列文章总结和导读
    jQuery插件实现select下拉框左右选择_交换内容(multiselect2side)
    php代码生成二维码
    微信公众平台开发(83) 生成带参数二维码
    MySQL主从问题
    mysql配置文件my.cnf
    网站UV,与IP、PV
    git基础使用小记
    系统运维
    [译]Profile and debug your ASP.NET MVC app with Glimpse
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4790486.html
Copyright © 2020-2023  润新知