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. 这道题让我 ...
随机推荐
- The client and server cannot communicate, because they do not possess a common algorithm
The client and server cannot communicate, because they do not possess a common algorithm This was re ...
- Dedecms判断当前栏目下是否有子栏目
使用dedecms建网站,有时为了某种功能的需要,需要通过代码判断当前栏目下是否有子栏目,如果有,显示一种样式,如果没有,显示另一种样式. dedecms判断当前栏目下是否有子栏目可使用以下的代码进行 ...
- 【Excel】输出CSV文本
'******************************************************************************* ' CSV形式テキストファイル書き出す ...
- Webservice学习之WSDL详解
1. <definitions/> 这部分在基础篇里已经介绍,主要说明引用了哪些schema以及schema的位置等,可以看下基础篇的介绍,SayHello的Demo这部分内容如下: &l ...
- CentOS7安装Go环境
下载go(我的当前目录是/data/work)$wget https://studygolang.com/dl/golang/go1.10.1.linux-amd64.tar.gz$tar -xvf ...
- 剑指offer题目java实现
Problem2:实现Singleton模式 题目描述:设计一个类,我们只能生成该类的一个实例 package Problem2; public class SingletonClass { /* * ...
- MongoDB数据库去重
查询: db.patents_texts.aggregate([ { $group:{_id:{Patent_num:'$Patent_num',Patent_name:'$Patent_name'} ...
- mui APP与服务器之间的交互原理
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- MySQL数据库(增删查改)
创建一个表:create table user( uid varchar(10) , pwd int(10) ); 学生表: create table student( sno varchar(20) ...
- c++课设
#include <stdio.h>#include <time.h>#include <math.h>#define C 60000;struct Student ...