LeetCode----202. Happy Number(Java)

來源:互聯網
上載者:User

標籤:

 1 package isHappy202; 2 /* 3  * Write an algorithm to determine if a number is "happy". 4 A happy number is a number defined by the following process:  5 Starting with any positive integer, replace the number by the sum of the squares of its digits,  6 and repeat the process until the number equals 1 (where it will stay),  7 or it loops endlessly in a cycle which does not include 1.  8 Those numbers for which this process ends in 1 are happy numbers. 9  */10 11 public class Solution {12     /*13      * solution:14      * 115      * 2-4-16-37-58-89-145-42-20-416      * 3-9-81-65-6117      * 418      * 5-25-29-85-8919      * 6-36-45-41-17-5020      * 7-49-97-130-1021      * 8-64-52-2922      * 9-81-6523      * so only 1 and 7 is "happy"24      */25     public static boolean isHappy(int n) {26         while(n/10>0){27             int sum=0;28             while(n/10>0){29                 sum+=Math.pow((n%10),2);30                 n=n/10;31             }32             sum+=Math.pow(n,2);33             n=sum;    34         }35         if (n==1||n==7)36             return true;37         return false;38     }39     public static void main(String[] args) {40         // TODO Auto-generated method stub41         System.out.println(isHappy(23456));42     }43 }

 

LeetCode----202. Happy Number(Java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.