zoukankan      html  css  js  c++  java
  • LeetCode -- Add Digits

    Question:

    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?

    Analysis:

    问题描述:给出一个非负的证书,重复把他的各位数加起来直至最后为个位数。

    思考:你能够不用循环而在O(1)的时间内完成这道题目嘛?

    思路一:模仿题目运算的过程,当加起来不是个位数时就把每一位都相加。

    思路二:如果不用循环,没有想到思路啊。。参考了网络上得答案后有所启发,返回的数肯定都在0-9之间,因此找到他们的规律即可。

    Answer:

    思路一:

    public class Solution {
     public int addDigits(int num) {
           while(num >= 10){
                      ArrayList<Integer> l = new ArrayList<Integer>();
               while(num/10 != 0) {
                       l.add(num%10);
                       num = num/10;
               }
              l.add(num);
              num = 0;
              for(int i=l.size()-1; i>=0; i--) {
                      num += l.get(i);
              }
           }
           return num;
        }
       
    }

    思路二:

    public class Solution {
        public int addDigits(int num) {
            if(num < 10)
                return num;
            return (num - 1)% 9 + 1;
        }
    }
  • 相关阅读:
    01.html5+phonegap跨平台移动应用开发
    10个CSS简写/优化技巧
    JS高级学习历程-17
    JS高级学习历程-16
    算法详解之Tarjan
    分层图详解
    洛谷 题解 P1196 【[NOI2002]银河英雄传说】
    洛谷 题解 P1220 【关路灯 】
    洛谷 题解 P1352 【没有上司的舞会】
    二维前缀和详解
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4832204.html
Copyright © 2011-2022 走看看