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?

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    题意:给定一个非负整数,将其每位上的数字加起来,重复此操作,直到相加的和为一位数
    follow up:要求时间复杂度为O(1),不使用循环或递归

    方法一:直接计算。但要使用循环。时间复杂度高

    public int addDigits(int num) {
            int sum = 0;
            while(num / 10 != 0){
                while(num % 10 != 0 || num != 0){
                    sum += num % 10;
                    num /= 10;
                }
                num = sum;
                sum = 0;
            }
            return num;
        }

    方法二:参考:https://www.cnblogs.com/grandyang/p/4741028.html

    可看出:c3列每个数相加,变成对应的c2列;而c2列的每个数相加,又变成对应的c1列。
    可得出规律:每9个数为一个循环,所求的sum为num除以9取余,即num % 9。但是存在一个问题,即像9、18、27这些除以9余数为0.
    因此为了对所有数都适用,改为:(num - 1) % 9 + 1

    public int addDigits(int num){
            return (num - 1) % 9 + 1;
        }
  • 相关阅读:
    《机器学习十讲》学习报告七
    找到每个人的任务
    牛客每个人最近的登陆日期
    考试分数(一)
    牛客的课程订单分析(一)
    实习广场投递简历分析(一)
    sql 查找最晚入职员工信息
    sql 学习笔记
    shell 编程获取文件名后缀为特定字符的函数
    im的基本思路
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/8196226.html
Copyright © 2011-2022 走看看