258. Add Digits 入学考试:数位相加

本文介绍了一种通过不断累加数字直至只剩一位数的算法实现,并提供了完整的Java代码示例。该算法适用于任何非负整数,通过迭代直至得到最终结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[抄题]:

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

Example:

Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
             Since 2 has only one digit, return it.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

while循环写得太少,潜意识里还是for循环

 

//id: yuec2 name:Yue Cheng
package day1test;

import java.util.Scanner;

public class Numerologist {

    public static void main(String[] args) {
        Numerologist n = new Numerologist();
        System.out.println("Enter an integer");
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        System.out.println("Your lucky number is " + n.getLuckyNumber(number));
        input.close();
    }

    
    int getLuckyNumber(int num) {
        //write your code here
        int number = Math.abs(num);
        String str = String.valueOf(number);
        char digits[] = str.toCharArray();
        while (digits.length != 1) {
            int sum = 0;
            for (int i = 0; i < digits.length; i++) {
                sum += digits[i] - 'a';
            }
            str = String.valueOf(sum);
            digits[] = str.toCharArray();
        }
        
        if (digits.length == 1)
        {
            int result = digits[0] - 'a';
            return result;
        }
        return 0;
    }
}

 

 

 

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

最基本的while循环吧

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

corner case没注意,小于10的数字直接返回num本身

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

练习多写while循环吧

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

 

class Solution {
    public int addDigits(int num) {
        //corner case
        if (num == 0) return 0;
        
        //while loop
        while (num >= 10) {
            int sum = 0;
            //add every digit
            while (num > 0) {
                sum += num % 10;
                num /= 10;
            }
            //assign the sum to the new num
            num = sum;
        }
        
        //return
        return num;
    }
}
View Code

 

转载于:https://www.cnblogs.com/immiao0319/p/9589898.html

### C++ 实现数位相加且结果不超过指定值 在处理数位相加时,如果需要确保最终的结果不超过某个特定的最大值 \( a \),可以采用逐位累加的方式,并引入一个额外的条件来判断当前累加后的总和是否会超出给定范围。下面是一个具体的实现方法: #### 方法概述 为了防止溢出,在每次执行加法操作之前先检查加上新数值之后会不会使累积量大于设定界限 \( a \);一旦发现即将越界,则停止进一步运算并给出提示。 #### 代码实例 这里提供了一个简单的函数 `addDigitsWithLimit` 来完成上述功能: ```cpp #include <iostream> #include <string> using namespace std; // Function to add digits with limit check bool addDigitsWithLimit(const string& numStr, int maxSum){ int sum = 0; for (char digit : numStr){ // Iterate over each character in the input string if (!isdigit(digit)){ cout << "Invalid number format." << endl; return false; // Return on invalid characters found within the string. } int currentDigit = digit - '0'; // Convert char to integer // Check whether adding this digit would exceed our maximum allowed value if ((sum + currentDigit) > maxSum){ cout << "Adding next digit will cause overflow beyond limit of " << maxSum << "." << endl; return false; }else{ sum += currentDigit; } } cout << "Final Sum is: " << sum << ", which does not exceed the specified limit."; return true; } int main(){ string userInput; int maxValue; cout << "Enter numbers as a single continuous sequence without spaces or commas:" << endl; cin >> userInput; cout << "\nEnter your desired upper bound for summation:" << endl; cin >> maxValue; bool resultStatus = addDigitsWithLimit(userInput,maxValue); if(resultStatus==true){ cout<<"\nOperation completed successfully!"<<endl; } else { cout<<"\nThe operation was interrupted due to potential overflow conditions."<<endl; } return 0; } ``` 此程序接收用户输入的一串连续数字字符以及最大允许求和上限作为参数,遍历这些字符并将它们转换成对应的整型数据进行累加。每当准备加入下一个数字前都会做一次边界检测,当预测到可能发生的溢出会立即终止循环并向用户提供反馈信息[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值