【嘎】整数-整数的各位积和之差
题目:
给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
示例 1:
输入:n = 234
输出:15
解释:
各位数之积 = 2 * 3 * 4 = 24
各位数之和 = 2 + 3 + 4 = 9
结果 = 24 - 9 = 15
示例 2:
输入:n = 4421
输出:21
解释:
各位数之积 = 4 * 4 * 2 * 1 = 32
各位数之和 = 4 + 4 + 2 + 1 = 11
结果 = 32 - 11 = 21
提示:
1 <= n <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer
class Solution { public int subtractProductAndSum(int n) { String nstr = n + ""; int sum = 0; int product = 1; // 这里不能写0啊笨蛋 int diff = 0; for (int i = 0; i < nstr.length(); i++) { char c = nstr.charAt(i); sum += Integer.parseInt(c + ""); product *= Integer.parseInt(c + ""); } System.out.println(sum); System.out.println(product); diff = product - sum; return diff; } }
当时只想到了把它变成字符串然后逐个取成int,后来看了题解,可以用 % 和 / 来
class Solution { public int subtractProductAndSum(int n) { int sum = 0; int product = 1; // 这里不能写0啊笨蛋 int diff = 0; while(n != 0) { sum += n % 10; product *= n % 10; n = n / 10; } diff = product - sum; return diff; } }
所以要多想想本身这个类型能不能完成题目的要求~
越努力越幸运~ 加油ヾ(◍°∇°◍)ノ゙