前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >05 Subtract the Product and Sum of Digits of an Integer

05 Subtract the Product and Sum of Digits of an Integer

作者头像
devi
发布2021-08-18 15:50:38
2300
发布2021-08-18 15:50:38
举报
文章被收录于专栏:搬砖记录

题目

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Example 1:

Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15

Example 2:

Input: n = 4421 Output: 21 Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21

Constraints:

代码语言:javascript
复制
1 <= n <= 10^5

解析

题目通俗易懂,不多做解释。 解题关键就在于获取到一个数的每位数—>取余10再除以10,重复操作即可 如123 123%10=3 123/10=12 12%10=2 12/10=1 1%10=1

答案

代码语言:javascript
复制
class Solution {
    public int subtractProductAndSum(int n) {
        int product=1;
        int sum=0;
        while(n>0){
            int tmp=n%10;
            product*=tmp;
            sum+=tmp;
            n/=10;
        }
        return product-sum;
    }
}
在这里插入图片描述
在这里插入图片描述

评论区似乎没有其他更好的解法。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/01/20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解析
  • 答案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档