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. 这道题让我 ...
随机推荐
- OpenGL着色器入门简介
说明:本文翻译自LearnOpengl经典教程,OpenGL着色器基础介绍的比较通俗易懂,特总结分享一下! 为什么要使用着色器?我们知道,OpenGL一般使用经典的固定渲染管线来渲染对象,但是随着Op ...
- [sqoop] sqoop 小试牛刀
sqoop 1.4.6 小试牛刀 sqoop import 参数 1. mysql导入 到hdfs中 ./sqoop import --connect jdbc:mysql://mysql:3306 ...
- nginx出现 “414 request-uri too large”
nginx出现 “414 request-uri too large” 在请求查询的时候使用了Get方法,由于拼接的url过长,导致nginx出现了“414 request-uri too large ...
- vb编程中的选择结构语句的写法
1996年,Bohra和Jacopin提出了结构化算法的3中种基本结构:顺序结构.选择结构和循环结构 目前已经得到证明,无论多么复杂的程序,都是由上面的3种基本结构中的一种或者多种的组合构成 在此笔者 ...
- css的position中absolute和fixed的区别
fixed:固定定位 absolute:绝对定位 区别很简单: 1.没有滚动条的情况下没有差异 2.在有滚动条的情况下,fixed定位不会随滚动条移动而移动,而absolute则会随滚动条移动 常用场 ...
- js中的运算符优先级
运算符有何很多,基本的可能都比较熟,单有些优先级很难记住.建议使用“()”将复杂的运算表达式区分好优先级. 我给运算符优先级做了一首小打油诗. 括号成员new函数 直new后置累计数 单目幂算乘除模 ...
- E - Closest Common Ancestors
Write a program that takes as input a rooted tree and a list of pairs of vertices. For each pair (u, ...
- git checkout --theirs(ours)
假设原来有文件A,程序员甲把A进行了完全的重写,而甲在自己的branch工作的同时,他的同事程序员乙则对A进行了一个优化.这样,当甲想要merge的时候,A文件就有很多的冲突,可能多达几百行. 这时候 ...
- canvas霓虹雨
在codepen上看到一个Canvas做的下雨效果动画,感觉蛮有意思的.就研究了下,这里来分享下,实现技巧.效果可以见下面的链接. 霓虹雨: http://codepen.io/natewiley/f ...
- 查看oracle数据库是否为归档模式
查看oracle数据库是否为归档模式 [1] 1.select name,log_mode from v$database; NAME LOG_MODE --------------- ...