zoukankan      html  css  js  c++  java
  • LeetCode 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.
    1 public class Solution {
    2     public int addDigits(int num) {
    3         return (num-1) % 9 + 1;
    4     }
    5 }
     1 /*************************************************************************
     2     > File Name: LeetCode258.c
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: Tue 10 May 2016 07:44:57 PM CST
     6  ************************************************************************/
     7 
     8 /*************************************************************************
     9 
    10     Add Digits
    11     
    12     Given a non-negative integer num, 
    13     repeatedly add all its digits until the result has only one digit.
    14 
    15     For example:
    16 
    17     Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. 
    18     Since 2 has only one digit, return it.
    19 
    20     Follow up:
    21     Could you do it without any loop/recursion in O(1) runtime?
    22 
    23     Hint:
    24 
    25     A naive implementation of the above process is trivial. 
    26     Could you come up with other methods?
    27     What are all the possible results?
    28     How do they occur, periodically or randomly?
    29     You may find this Wikipedia article useful.
    30 
    31  ************************************************************************/
    32  
    33 #include <stdio.h>
    34 
    35 int addDigits( int num )
    36 {
    37     int ret = (num-1) % 9+ 1;
    38     return ret;
    39 }
    40 
    41 int main()
    42 {
    43     int n = 38;
    44     int ret = addDigits(n);
    45     printf("%d
    ", ret);
    46     return 0;
    47 }
  • 相关阅读:
    hdu2717 Catch That Cow
    hdu1017
    Html5 学习笔记 【PC固定布局】 实战2 导航栏搜索区域
    Html5 学习笔记 【PC固定布局】 实战1 导航栏
    Html5 学习笔记 Sublime text3 和 Emmet 插件
    Html5 学习笔记 --》布局
    Html5 学习笔记 --》css3 学习
    Html5 学习笔记 --》html基础 css 基础
    数据库备份
    spring boot 尚桂谷学习笔记11 数据访问03 JPA
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5428842.html
Copyright © 2011-2022 走看看