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. 这道题让我 ...
随机推荐
- 手写一个selenium浏览器池
维护一组浏览器,实现每分钟1000次查询.DriverPool使用变幻版只初始化一次的单例模式.维护每个浏览器的当前是否使用的状态. 不需要等待请求来了,临时开浏览器,开一个浏览器会耽误6秒钟. 可以 ...
- 【Excel】读取CSV文本
Option Explicit ' CSV形式テキストファイル(5カラム)読み込みサンプル Sub READ_TextFile() Const cnsTITLE = "テキストファイル読み込 ...
- 关闭win10一切
狂客原创,转载请注明来源 关闭更新 注册表(以管理员身份运行) 计算机\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ Start值 ...
- 二、Sql Server 基础培训《进度2-关于主键(知识点学习)》
学习作业2: 问题1:主键都有哪些方式? 问题2:本次实战案例建立的主键采用哪种方式? 问题3:猜猜金蝶K3WISE建立的主键采用哪种方式? 问题4:谈谈手工主键增长设置具体实现思路?(选 ...
- C#GDI+ 绘制线段(实线或虚线)、矩形、字符串、圆、椭圆
C#GDI+ 绘制线段(实线或虚线).矩形.字符串.圆.椭圆 绘制基本线条和图形 比较简单,直接看代码. Graphics graphics = e.Graphics; //绘制实线 )) { pen ...
- word2vec:基本的安装及使用简介
官方word2vec的github下载地址:https://github.com/svn2github/word2vec 环境,linux-ubuntu-14.04LST,安装好git, gcc版本4 ...
- R - Dividing 多重背包
来源poj1059 Marsha and Bill own a collection of marbles. They want to split the collection among thems ...
- Tcp/IP 的四层模型
维基:https://zh.wikipedia.org/wiki/TCP/IP%E5%8D%8F%E8%AE%AE%E6%97%8F 因特网协议组 LITA 因特网协议组 Link 网络接口层 以太 ...
- 【C++ 继承与派生/知识梳理】
为什么引入继承派生 代码重用扩充 软件的复用 层次分类 派生类的语法定义 class 派生类名(1):继承方式(2) 基类名(3){ 派生成员声明:} *(1)一个派生类——>多个基类,多继 ...
- 时间选择器(timepicker)
可以使用Slider拖动选择,也可以使用timespinner改变时间,或者手工填写. 自动判断位置 效果: 源码: <!DOCTYPE html> <html xmlns=&quo ...