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;
        }
    }
  • 相关阅读:
    第二次作业循环语句
    c语言01次作业分支,顺序结构
    PAT 1027. Colors in Mars
    PAT 1026 Table Tennis
    PAT 1035 Password
    PAT 1038. Recover the Smallest Number
    PAT 1028 List Sorting (25)
    PAT 1041 Be Unique (20)
    PAT 1025 PAT Ranking
    1037. Magic Coupon
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4832204.html
Copyright © 2011-2022 走看看