zoukankan      html  css  js  c++  java
  • [Leetcode] Happy Number

    1.先上题

    Write an algorithm to determine if a number is "happy".

    A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

    2.happy number

    (先说一下happy number的特点,这个题暂时用不到。。)

    如果一个数是happpy number,那么在验证的过程中求出来的的所有的平方和组成的序列也都是happy number.比如19是happy number,(82,68,100)也都是。如果一个数不是,同理。。。平方和序列也都不是。而且happy number每一位重新组合,新的数字也是happy number.(比如91)。在happy number中的任何位置插入0 ,新数字都是happy number。

    happy number的详细介绍见http://en.wikipedia.org/wiki/Happy_number

    3.分析

        3.1结束条件

          如果一个数,它每一位数字的平方和等于1 ,这个数就是happy number;如果在计算的过程中,没有平方和等于1的,而且出现了循环,就不是happy number。

        3.2可以用HashSet记录计算的过程中得到的平方和序列,HashSet<>中的值不能重复且没有顺序,而且容量会按需自动增长。

    4.代码

    public boolean isHappy(int n) {

    if(n<=0) return false;
    HashSet<Integer> showedNum=new HashSet<>();

    while(n<=Integer.MAX_VALUE){
    if(showedNum.contains(n)) return false;
    else showedNum.add(n);
    n=digitSquare(n);
    if(n==1) {
    // System.out.println("yes");
    return true;
    }
    }
    return false;
    }
    public int digitSquare(int n){
    int s=0,temp;
    while(n!=0){
    temp=n%10;
    s+=temp*temp;
    n=n/10;
    }
    return s;
    }

  • 相关阅读:
    银行业务调度系统
    Apache虚拟主机配置
    linux下 redis 启动
    linux下mysql 启动命令
    linux 查看磁盘空间大小
    基于微信地理位置的附近商家距离坐标数据查询方法
    mysql表无权限访问
    linux用户操作
    Java中Date各种相关用法
    spring 定时任务的 执行时间设置规则
  • 原文地址:https://www.cnblogs.com/summer323/p/4484910.html
Copyright © 2011-2022 走看看