Problem:

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.

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

Analysis:

This problem is actually very very easy!
The problem has actually described the algorithm very clearly! We just need to implement it! Choice: you want to do all those operations
82 : 8^2 + 2^2 = 68
in one step or not?
If it was done in one step, in one loop,
we need to first get each digit and sum the square of them together.
The digit operation is always hard to implement compared with other logic, we should not mix them together. Why not separte those two major operation out?
Step 1: Get the digit array of a integer.
private int[] get_array(int n) {
String str = String.valueOf(n);
int len = str.length();
int[] ret = new int[len];
for (int i = 0; i < len; i++) {
int digit_weight = (int)Math.pow(10, len-i-1);
ret[i] = n / digit_weight;
n = n % digit_weight;
}
return ret;
} Skill: firstly convert n into string type, then we can get the length information through the str.length().
String str = String.valueOf(n);
int len = str.length();
int[] ret = new int[len]; Step 2: Sum each digit of the int array together.
private int sum(int[] a) {
int ret = 0;
for (int i = 0; i < a.length; i++)
ret += a[i] * a[i];
return ret;
} Main:
According to the description, the number would end up with "1" or a circular digital sequence.
If the circular situation happens, we definitely not want to avoid the infinite loop.
Use our old friend : HashSet, we could easily achieve that point.
HashSet<Integer> hash_set = new HashSet<Integer> ();
while (!hash_set.contains(n)) {
hash_set.add(n);
n = sum(get_array(n));
if (n == 1)
return true; }
return false;

Solution:

public class Solution {
public boolean isHappy(int n) {
if (n < 0)
throw new IllegalArgumentException("The passed in n is negative!");
HashSet<Integer> hash_set = new HashSet<Integer> ();
while (!hash_set.contains(n)) {
hash_set.add(n);
n = sum(get_array(n));
if (n == 1)
return true;
}
return false;
} private int[] get_array(int n) {
String str = String.valueOf(n);
int len = str.length();
int[] ret = new int[len];
for (int i = 0; i < len; i++) {
int digit_weight = (int)Math.pow(10, len-i-1);
ret[i] = n / digit_weight;
n = n % digit_weight;
}
return ret;
} private int sum(int[] a) {
int ret = 0;
for (int i = 0; i < a.length; i++)
ret += a[i] * a[i];
return ret;
}
}

[LeetCode#202] Roman to Integer的更多相关文章

  1. [LeetCode][Python]Roman to Integer

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/roman-t ...

  2. 【LeetCode】Roman to Integer & Integer to Roman

    Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within t ...

  3. Leetcode#13. Roman to Integer(罗马数字转整数)

    题目描述 罗马数字包含以下七种字符:I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即 ...

  4. leetcode:Roman to Integer and Integer to Roman

    2015-06-03 罗马数字以前接触过I到VIII比较多,直到遇见这个题目才知道更详细.阿拉伯数字和罗马数字之间的转换最重的是了解罗马数字的规则. 罗马数字规则:(总结) 1, 罗马数字共有7个,即 ...

  5. Leetcode 13. Roman to Integer(水)

    13. Roman to Integer Easy Roman numerals are represented by seven different symbols: I, V, X, L, C, ...

  6. leetcode:Roman to Integer(罗马数字转化为罗马数字)

    Question: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the rang ...

  7. [LeetCode] 13. Roman to Integer 罗马数字转化成整数

    Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 ...

  8. 【leetcode】Roman to Integer

    题目描述: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range fr ...

  9. 【JAVA、C++】LeetCode 013 Roman to Integer

    Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 t ...

随机推荐

  1. angularjs filter cut string

    angular.module('App.controllers.MyCtrl', []) .controller('MyCtrl', function (my) {}) .filter('cut', ...

  2. Prototype 原型模式

    用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象. 原型模式即在运行时动态的通过一个对象的实例来创建这个类的对象,可以理解成通过一个实例克隆出另一个实例. Prototype模式的一些优 ...

  3. android获取Mac地址和IP地址

    获取Mac地址实际项目中测试了如下几种方法:(1)设备开通Wifi连接,获取到网卡的MAC地址(但是不开通wifi,这种方法获取不到Mac地址,这种方法也是网络上使用的最多的方法) //根据Wifi信 ...

  4. 利用jQuery npoi插件 asxh一般处理文件实现excel的下载

    最近开发的过程中遇到这么一个问题,利用ajax和ashx文件实现下载功能.发现代码调试走完之后并没有弹出下载框. 研究了一段时间之后发现解决这种问题有两种方法,1.ajax获取数据集在前台做处理实现导 ...

  5. 防御SQL注入的方法总结

    这篇文章主要讲解了防御SQL注入的方法,介绍了什么是注入,注入的原因是什么,以及如何防御,需要的朋友可以参考下   SQL 注入是一类危害极大的攻击形式.虽然危害很大,但是防御却远远没有XSS那么困难 ...

  6. [上传下载] C# UpLoadFiles文件上传类 (转载)

    点击下载 UpLoadFiles.zip 主要功能如下 /// <summary> /// 上传文件 /// </summary> /// <param name=&qu ...

  7. 在Android上模拟登录广工正方教务系统查询成绩

    这是在博客园里开博以来写的第一篇博客. 因为之前看过很多人都有发过关于模拟登录正方软件获取数据的文章,自己觉得挺好玩的便也去动手一做,开始还以为挺难的,但实际做起来还蛮简单的,当然其中还有些小插曲. ...

  8. 多个互相有联系的checkbox的单选逻辑

    checkbox单选的状态逻辑,状态好的时候一下就写好了,状态不好的时候要调试比较久,当然主要是对其中的事件不太清楚. 先给出效果图吧. 然后给出代码, selectZhiFuBaoPay.setOn ...

  9. sql server split函数

    --创建分割函数CREATE FUNCTION dbo.Split(@String varchar(8000),@Delimiter char(1))returns @temptable TABLE ...

  10. 关于wordpress中更换CKEditor编辑器

    wordpress中自带的编辑器实在是功能太简,连插入表格都没有,使用插件的方式太过于麻烦,干脆就直接更换编辑器了,在网上找了一些方法,下文引自http://down.chinaz.com/try/2 ...