LeetCode (258):Add Digits
来源:互联网 发布:海康网络视频服务器 编辑:程序博客网 时间:2024/06/03 17:23
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 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
这是一个数学问题(废话),写下几个例子你会发现每个结果都是num mod 9后的余数。
我的代码:
1 public class Solution { 2 public int addDigits(int num) { 3 if(num%9==0&&num>9){ 4 return 9; 5 } 6 if(num>=10){ 7 num=num%9; 8 } 9 return num;10 }11 }
这是我一开始的代码,其实我只是想解决下边界问题。之后看了网上的代码,顿时感觉我的代码有点傻。
修改后:
public class Solution { 2 public int addDigits(int num) { 3 return 1+(num-1)%9;10 }11 }
阅读全文
0 0
- leetcode 258: Add Digits
- 258Add Digits - LeetCode
- leetCode #258 Add Digits
- [LeetCode 258] Add Digits
- LeetCode(258)Add Digits
- leetcode-258-Add Digits
- [leetcode 258]Add Digits
- [Leetcode]#258 Add Digits
- LeetCode 258----Add Digits
- LeetCode 258 : Add Digits
- 【LeetCode】258 Add Digits
- Leetcode - 258 - Add Digits
- leetcode 258 :Add Digits
- leetcode 258--Add Digits
- leetcode 258 Add Digits
- Leetcode #258 Add Digits
- LeetCode 258:Add Digits
- LeetCode 258:Add Digits
- Java Swing简单的加法器
- 基于tiny4412开发板led灯字符设备ioctl驱动写法
- C++求矩阵的鞍点
- 分布式入门:副本控制
- Matlab重新激活
- LeetCode (258):Add Digits
- java输出前50个素数
- 关于seo写作内容的一些探讨
- LeetCode (237):Delete Node in a Linked List
- 技术的热门度曲线
- LeetCode (65):Same tree
- 在centos7测试arm-Linux-gcc交叉编译器
- LeetCode (226):Invert Binary Tree 递归实现
- LeetCode (236):Lowest Common Ancestor of a Binary Search Tree