zoukankan      html  css  js  c++  java
  • 【嘎】整数-整数的各位积和之差

    题目:

    给你一个整数 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;
        }
    }

    所以要多想想本身这个类型能不能完成题目的要求~ 

    越努力越幸运~ 加油ヾ(◍°∇°◍)ノ゙
  • 相关阅读:
    ExtJS学习之路第一步:对比jQuery,认识ExtJS
    创建Windows服务(C++)
    吴恩达2014机器学习教程笔记目录
    在Hexo中渲染MathJax数学公式
    Linux服务器性能检测命令集锦
    Redis开启AOF导致的删库事件
    从表扩展增加列属性说起
    数据库规约解读
    MySQL规约(阿里巴巴)
    HDFS运行原理
  • 原文地址:https://www.cnblogs.com/utomboy/p/12619144.html
Copyright © 2011-2022 走看看