leecode 解题总结:258. Add Digits

数字压缩至单个位数算法
本文介绍了一个算法问题,即如何将一个非负整数的所有位数反复相加直至结果仅剩一位数的过程,并提供了一种实现方法,包括数字拆分与累加的步骤。同时探讨了在不使用循环或递归的情况下,如何在O(1)时间内完成此任务。
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

分析:这里的一位是指在十进制下面,只剩一位数
最简单的情况是:先分解然后相加每一位,
如果不使用循环或者递归,在O(1)时间完成。肯定只需要计算一遍
38,
3: 0011
8: 1000
异或操作:变为11
   1011

如果是33: 3 + 3 = 6,6+0=6这样不是永远
0011
0011
0000

输入:
33
38
1
100
输出:
6
2
1
1
*/

class Solution {
public:
	//将一个数的各个位进行拆分,返回拆分后的累加和。
	//拆分使用先 % 10 后 / 10的方法 
	int getResult(int num)
	{
		vector<int> result;
		int temp;
		do
		{
			temp = num % 10;
			result.push_back(temp);
			num /= 10;
		}while(num);
		//遍历求得累加和
		int sum = 0;
		if(result.empty())
		{
			return 0;
		}
		int size = result.size();
		for(int i = 0 ; i < size ; i++)
		{
			sum += result.at(i);
		}
		return sum;
	}

    int addDigits(int num) {
		int result = num;
		while(result >= 10)
		{
			result = getResult(result);
		}
		return result;
    }
};


void process()
{
	 int num;
	 Solution solution;
	 while(cin >> num )
	 {
		 int answer = solution.addDigits(num);
		 cout << answer << endl;
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值