LeetCode258 各位相加
题目链接:https://leetcode-cn.com/problems/add-digits/
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
示例:
输入:38
输出: 2
解释: 各位相加的过程为:3 + 8 = 11,1 + 1 = 2。 由于2是一位数,所以返回 2。
进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
常规思路:
int addDigits(int x) {
if(x<) return x;
int sum=;
while(x){
sum+=x%;
x/=;
}
return addDigits(sum);
}
优化后的:找规律%9
int addDigits(int x) {
if(x==) return ;
else if(x%==) return ;
else return x%;
}
LeetCode258 各位相加的更多相关文章
- [Swift]LeetCode258. 各位相加 | Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. ...
- [LeetCode258] Add Digits 非负整数各位相加
题目: Given a non-negative integer num, repeatedly add all its digits until the result has only one di ...
- LeetCode 258. 各位相加(Add Digits)
258. 各位相加 258. Add Digits 题目描述 给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数. LeetCode258. Add Digits 示例: 输入: 3 ...
- T-SQL字符串相加之后被截断的那点事
本文出处:http://www.cnblogs.com/wy123/p/6217772.html 字符串自身相加, 虽然赋值给了varchar(max)类型的变量,在某些特殊情况下仍然会被“截断”,这 ...
- [LeetCode] Add Strings 字符串相加
Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. ...
- [LeetCode] Add Binary 二进制数相加
Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...
- [LeetCode] Add Two Numbers 两个数字相加
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- C语言关于利用sscanf实现字符串相加减
#include<stdio.h>#include<string.h>void main(){ int a; int b; char str1[10] = "9999 ...
- [CareerCup] 18.1 Add Two Numbers 两数相加
18.1 Write a function that adds two numbers. You should not use + or any arithmetic operators. 这道题让我 ...
随机推荐
- Windows补丁更新Tips
1.Windows 2012 R2 MS14-066补丁安装失败 现象:下载对应版本的补丁,提示“此更新不适用于你的计算机” 解决:使用命令行可成功安装 @echo off expand –F:* d ...
- vue---computed计算属性的使用
一直以来在使用vue的时候,会对vue的computed属性和watch属性具体的使用分不清楚,总算花点时间整理了下. computed:通常用于监控自己定义的变量,这个变量可以不再data中定义,直 ...
- cs231n(三) 误差反向传播
摘要 本节将对反向传播进行直观的理解.反向传播是利用链式法则递归计算表达式的梯度的方法.理解反向传播过程及其精妙之处,对于理解.实现.设计和调试神经网络非常关键.反向求导的核心问题是:给定函数 $f( ...
- B - Assignment
Tom owns a company and he is the boss. There are n staffs which are numbered from 1 to n in this com ...
- mysql数据库转成oracle踩过的坑
1.使用count这种组函数,那么必须配合group by使用,获取的字段要么出现在组函数内要么出现在group by中2.oracle使用union不仅要字段名一致并且数据类型也要一致3.REGEX ...
- 把一张图片变成base64
// image_file可为urlprivate function base64EncodeImage($image_file) { $image_info = getimagesize($imag ...
- 手把手教你提交文件到git
手把手教你使用git提交到github 作者 数据分析与优化 关注 2016.07.17 10:25 字数 7342 阅读 399评论 1喜欢 6 摘要Git是分布式版本控制系统,那么它就没有中央服务 ...
- 最全的MonkeyRunner自动化测试从入门到精通(4)
Android Sdk环境变量配置步骤一:我们进行再eclipse中下载sdk来进行使用. 在安装ADT插件完成之后,在eclipse的菜单界面会多一个ADT的管理器,如下图,点击进入到安卓API安装 ...
- 4、 LwIP协议栈规范翻译——流程模型
4.流程模型 协议实现的流程模型描述了系统被划分为不同的流程的方式.用于实现通信协议的一个流程模型是让每个协议作为一个独立的进程运行.有了这个模型,严格的协议分层被强制执行,并且协议之间的通信点必须严 ...
- 保存退出vi编辑
保存命令按i进入编辑模式,编辑完成按ESC键 跳到命令模式,然后: :w 保存文件但不退出vi:w file 将修改另外保存到file中,不退出vi:w! 强制保存,不推出vi:wq 保存文件并退出v ...