Java实现 LeetCode 258 各位相加
258. 各位相加
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
示例:
输入: 38
输出: 2
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
找规律。假设 num = 384 = 3 * 100 + 8 * 10 + 4
第一轮计算 sum = 15 = 3 + 8 + 4
差值 = 3 * 99 + 8 * 9 = (3 * 11 + 8) * 9 即差值为9的倍数
第二轮计算 num = 15 = 1 * 10 + 5
sum = 6 = 1 * 0 + 5
差值 = 9
由此得出规律:num % 9
注意:需要注意 9 的整倍数最终结果应该返回9,小于10的数直接返回
class Solution {
public int addDigits(int num) {
return (num-1)%9+1;
}
}
Java实现 LeetCode 258 各位相加的更多相关文章
- LeetCode 258. 各位相加(Add Digits)
258. 各位相加 258. Add Digits 题目描述 给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数. LeetCode258. Add Digits 示例: 输入: 3 ...
- Leetcode -- 258 数位相加
258. Given a non-negative integer num, repeatedly add all its digits until the result has only one d ...
- Leetcode——258.各位相加【水题】
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数. 示例: 输入: 38 输出: 2 解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2. 由于 2 是一位数,所 ...
- LeetCode(258.各位相加)的思路及解决过程
问题如下: 给一个非负整数 num,反复添加所有的数字,直到结果只有一个数字. 例如: 设定 num = 38,过程就像: 3 + 8 = 11, 1 + 1 = 2. 由于 2 只有1个数字,所以返 ...
- leetcode 258. 各位相加 (python)
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数. 示例: 输入: 38输出: 2 解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2. 由于 2 是一位数,所以 ...
- Java实现 LeetCode 415 字符串相加
415. 字符串相加 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和. 注意: num1 和num2 的长度都小于 5100. num1 和num2 都只包含数字 0-9. num ...
- LeetCode:字符串相加【415】
LeetCode:字符串相加[415] 题目描述 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和. 注意: num1 和num2 的长度都小于 5100.num1 和num2 都只 ...
- Java for LeetCode 216 Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
- Java for LeetCode 214 Shortest Palindrome
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. ...
随机推荐
- 谈谈R语言的缺点和优点
编码不友好,对中文不友好,逼着你用RStudio.Jupyter Notebook/Jupyter Lab.图标丑,每次点击感觉辣眼睛. 为节省内存,R语言计算默认有效数字为7位,比Excel的15位 ...
- 经典sql语句大全,【转载】
经典SQL查询语句大全 一.基础1.说明:创建数据库CREATE DATABASE database-name2.说明:删除数据库drop database dbname3.说明:备份sql se ...
- Intellij Idea2018破解教程(激活到2099年)
1.下载IntelliJ IDEA 2018.1.6 链接:https://pan.baidu.com/s/18ZcKiPp3LU5S-la10r5icw 提取码:ghn0 2.安装IntelliJ ...
- 十分钟看懂AES加密
十分钟看懂AES加密算法 今天看了Moserware的<A Stick Figure Guide to the Advanced Encryption Standard(AES)>收获了不 ...
- Apache自定义404
先用命令找到httpd.conf文件在哪 find -name 'httpd.conf' 默认配置文件: vim /etc/httpd/conf/httpd.conf 然后找到项目的路径 <Di ...
- k8s搭建实操记录一(master)
#1)关闭CentOS7自带的防火墙服务 systemctl disable firewalld systemctl stop firewalld swapoff -a ##虚拟机要关闭交换 ...
- python函数总结,你值得拥有
目录 函数总结 函数定义与结构 函数名的使用 函数的参数 名称空间与作用域 名称空间 作用域 函数嵌套 内置函数(globals( ),locals( )) global+nonlocal 可迭代对象 ...
- oracle删除会话
create procedure killsessionas --set serveroutput on; --in oracle sql developer this cannot be ignor ...
- 如何覆盖elementUI样式
question: 在某个组件里面更改element-Ui的样式,而不影响全局. solution: 在需要更改的组件里新增一个style标签[重点:不要加scoped],然后直接获取class设置样 ...
- F. Machine Learning 带修端点莫队
F. Machine Learning time limit per test 4 seconds memory limit per test 512 megabytes input standard ...