siesteven

你要保守你心,胜过保守一切。因为一生的果效是由心发出。 --箴4:23
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

java1234教程系列笔记 S1 Java SE chapter 02 写乘法口诀表

Posted on 2016-12-29 23:59  siesteven  阅读(360)  评论(0编辑  收藏  举报

一、水仙花数

1、方式一:这是我的思路,取各个位数的方式。我个人习惯于使用取模运算。

public static List<Integer> dealNarcissiticNumberMethodOne(
            Integer startNum, Integer endNum) {
        List<Integer> resultList = new LinkedList<Integer>();
        for (Integer i = startNum; i <= endNum; i++) {
            Integer unitDigit = i % 10;
       // 该语句不够精炼,有冗余,应该写成 Integer tensDigit=i/10;即可 Integer tensDigit
= (i / 10) % 10; Integer hundredsDigit = (i / 100) % 10; if (i == (unitDigit * unitDigit * unitDigit + tensDigit * tensDigit * tensDigit + hundredsDigit * hundredsDigit * hundredsDigit)) { resultList.add(i); } } return resultList; }

2、方式二:视频的主讲人的方式如下:跟小学学习计数的方式一样。此时显示出数学理论的重要。

public static List<Integer> dealNarcissiticNumberMethodTwo(
            Integer startNum, Integer endNum) {
        List<Integer> resultList = new LinkedList<Integer>();
        for (Integer i = startNum; i <= endNum; i++) {
            Integer hundredsDigit = i / 100;
            Integer tensDigit = (i - hundredsDigit * 100) / 10;
            Integer unitDigit = i - hundredsDigit * 100 - tensDigit * 10;
            if (i == (unitDigit * unitDigit * unitDigit + tensDigit * tensDigit
                    * tensDigit + hundredsDigit * hundredsDigit * hundredsDigit)) {
                resultList.add(i);
            }
        }
        return resultList;
    }

 

二、乘法口诀

一段代码,调试了四次。需要运行看结果才倒推代码的缺陷。理想情况,应当是,先把逻辑梳理清楚。再梳理。切记

代码如下:

 1 public static String generateMultiplication(Integer startNum, Integer endNum) {
 2         String result = "";
 3         for (int i = startNum; i <= endNum; i++) {
 4             for (int j = startNum; j <= i; j++) {
 5                 result += j + "*" + i + "=" + i * j + " ";
 6             }
 7             result += "\n";
 8         }
 9         return result;
10     }