题目链接: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 各位相加的更多相关文章

  1. [Swift]LeetCode258. 各位相加 | Add Digits

    Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. ...

  2. [LeetCode258] Add Digits 非负整数各位相加

    题目: Given a non-negative integer num, repeatedly add all its digits until the result has only one di ...

  3. LeetCode 258. 各位相加(Add Digits)

    258. 各位相加 258. Add Digits 题目描述 给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数. LeetCode258. Add Digits 示例: 输入: 3 ...

  4. T-SQL字符串相加之后被截断的那点事

    本文出处:http://www.cnblogs.com/wy123/p/6217772.html 字符串自身相加, 虽然赋值给了varchar(max)类型的变量,在某些特殊情况下仍然会被“截断”,这 ...

  5. [LeetCode] Add Strings 字符串相加

    Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. ...

  6. [LeetCode] Add Binary 二进制数相加

    Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...

  7. [LeetCode] Add Two Numbers 两个数字相加

    You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...

  8. C语言关于利用sscanf实现字符串相加减

    #include<stdio.h>#include<string.h>void main(){ int a; int b; char str1[10] = "9999 ...

  9. [CareerCup] 18.1 Add Two Numbers 两数相加

    18.1 Write a function that adds two numbers. You should not use + or any arithmetic operators. 这道题让我 ...

随机推荐

  1. Mybatis面试题整理(超详细)

    1.什么是Mybatis? (1)Mybatis是一个半ORM(对象关系映射)框架,它内部封装了JDBC,开发时只需要关注SQL语句本身,不需要花费精力去处理加载驱动.创建连接.创建statement ...

  2. [sqoop] sqoop2 使用

    sqoop版本1.99.7 ,安装省略 1. 启动server sqoop2-server start 2. sqoop2-shell 链接 表示安装成功. 创建link 查看link 创建job 查 ...

  3. Linux常见问题整理

    1. 操作系统应该要控制硬件的哪些单元? 运算单元.控制单元.寄存器组.总线接口单元.输入/输出接口单元. 2. 一个较为完整的操作系统应该包含哪些部分? 比较完整的操作系统应该包含两个组件,一个是核 ...

  4. 21备忘录模式Memento

    一.什么是备忘录模式 Memento模式也叫备忘录模式,是行为模式之 一,它的作用是保存对象的内部状态,并在需要 的时候(undo/rollback)恢复对象以前的状态. 二.备忘录模式的应用场景 如 ...

  5. samba4.4security配置

    security=share在新版中已经被废弃了把security = share改为 security = user map to guest = Bad User 就可以了 [global] wo ...

  6. Win系统的快捷键

    用了Macos觉得win系统不好用,其实不然,win也有很多方便的快捷键. win系统的快捷键: super/Alt+Tab键切换应用程序,而不是用鼠标点,切换多任务,super就是win win+D ...

  7. maven的tomcat插件启动报错

    错误   :: java.lang.ClassCastException: org.springframework.web.filter.CharacterEncodingFilter cannot ...

  8. 一、HTML基础学习

    1.基本格式<html> <head><title></title></head> <body></body>< ...

  9. python换行语法错误

    a ={ ('住宅', 'https://auction.jd.com/getJudicatureList.html?callback=jQuery4392669&page=1&lim ...

  10. 使用LibreOffice修复受损的Office文档

    在工作中时常遇到Office文档损坏,用MS Office不能打开,有时候用LibreOffice(测试为4.2版本)可以打开,另存一下就好了. 此方法虽然不是100%管用,但在实际中大半都可以. 另 ...