题目描述
60、各位相加

PS:你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
不看PS的要求:
直接撸出代码:

class Solution {
    public int addDigits(int num) {
        	int x = 0;
		while (true) {
			x = 0;
			while (num > 0) {
				x += num%10;
				num /=10;
			}
			num = x;
			if(x <= 9){
				break;
			}	
		}		
		return x;
    }
}

那肯定效率很低
之后进行优化
看到O(1)就知道这道题有公式解:
根据这个博客来简单了解一下思路 https://blog.csdn.net/reuxfhc/article/details/80226547
60、各位相加

将代码撸出来:
注释的是上面的循环解法

	public static int addDigits(int num) {
        
		
		if(num == 0){
			return 0;
		}
		
		return (num-1) % 9 +1;
		
		/*int x = 0;
		if(num <= 9){
			return num;
		}
		while (true) {
			x = 0;
			while (num > 0) {
				x += num%10;
				num /=10;
				
			}
			num = x;
			
			if(x <= 9){
				break;
			}			
		}
		return x;*/
    }

再次验证数学对于计算机的推进作用
60、各位相加

相关文章:

  • 2022-12-23
  • 2022-02-08
  • 2021-08-04
  • 2022-12-23
  • 2022-02-20
  • 2021-08-19
  • 2022-12-23
  • 2021-12-04
猜你喜欢
  • 2021-05-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2022-12-23
  • 2021-06-27
相关资源
相似解决方案