zoukankan      html  css  js  c++  java
  • 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?

    分析:求各位数之和,并要求加到只有一位数为止。

    思路:因为是加法,很容易找规律,直接挨个列出结果。

    1    1
    2    2
    3    3
    4    4
    5    5
    6    6
    7    7
    8    8    
    9    9    
    10    1
    11    2
    12    3    
    13    4
    14    5
    15    6
    16    7
    17    8
    18    9
    19    1
    20    2

    基本可以确定规律 (num-1)%9+1

    JAVA CODE

    class Solution {
        public int addDigits(int num) {
            return (num - 1) % 9 + 1;
        }
    }
  • 相关阅读:
    Python变量常量命名
    代码格式
    Python 输入输出
    数据源
    LaTeX Test
    软件工程
    eclipse-智能提示设置
    java代码里设置指定颜色常值
    命令行中Vim直接打开某行
    Vim里快速替换命令
  • 原文地址:https://www.cnblogs.com/baichangfu/p/7482764.html
Copyright © 2011-2022 走看看