博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Add Digits
阅读量:6887 次
发布时间:2019-06-27

本文共 826 字,大约阅读时间需要 2 分钟。

Well, if you have no idea of other methods, try to compue the result for all the numbers ranging from 1 to 20 and then you will see the regularity. After you find it, this problem just needs 1-line code.

I write the following code.

1 class Solution { 2 public:3     int addDigits(int num) {4         return num - (num - 1) / 9 * 9; 5     } 6 };

This link writes anther more elegant one.

class Solution { public:    int addDigits(int num) {        return (num - 1) % 9 + 1;     } };

However, both of them cannot be used in Python since Python says that -1 % 9 = 8 and -1 / 9 = -1. Both the codes above will give a wrong answer for input 0. So you have to handle it separately.

1 class Solution:2     # @param {integer} num 3     # @return {integer}4     def addDigits(self, num):5         return (num - 1) % 9 + 1 if num else 0

 

转载地址:http://mtabl.baihongyu.com/

你可能感兴趣的文章
jquery实用的一些方法
查看>>
质数方阵
查看>>
jQuery $.each用法
查看>>
C语言结构体指针成员强制类型转换
查看>>
5.31 dockrer
查看>>
FreeCodeCamp----Intermediate Algorithm Scripting解法
查看>>
软件工程第二章 习题2 第4题
查看>>
《JavaScript设计模式与开发实践》读书笔记之命令模式
查看>>
hdu Problem 1242 Rescue bfs + 优先队列
查看>>
HDU-1507-Uncle Tom's Inherited Land*
查看>>
force里面的射线检测
查看>>
oracle 12.1.0.2中对象锁对系统的较大影响
查看>>
tensorboard的使用
查看>>
java进程占用CPU资源过高分析脚本
查看>>
day17--JQuery实例
查看>>
0312-css样式(选择器、文本text、字体fonts、背景background)
查看>>
【BZOJ】4358: permu 莫队算法
查看>>
powerdesigner 遇到的各种问题总结
查看>>
(转)韦东山linux学习笔记——ubuntu 9.10 软件源问题
查看>>
SQL错误
查看>>