返回信息流题目是leetcode上的,很简单:
Happy Number
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
1? + 9? = 82
8? + 2? = 68
6? + 8? = 100
1? + 0? + 0? = 1
我的myeclipse(jdk1.6)代码:
import java.util.HashSet;
public class Solution {
static HashSet<Integer> set = new HashSet<Integer>();
public static void main(String args[]){
System.out.print(isHappy(10)?"true":"false");
}
public static boolean isHappy(int n) {
if(n == 1)
return true;
Integer N = new Integer(n);
int length = N.toString().length();
int[] nums = new int[length];
for(int i = 0; i < length; i++){
nums[i] = n%10;
n = n /10;
}
int sum = 0;
for(int i : nums){
sum += i * i;
}
if(set.contains(sum))
return false;
set.add(sum);
return isHappy(sum);
}
}
结果:
leetcode上代码:
import java.util.HashSet;
public class Solution {
static HashSet<Integer> set = new HashSet<Integer>();
public boolean isHappy(int n) {
if(n == 1)
return true;
Integer N = new Integer(n);
int length = N.toString().length();
int[] nums = new int[length];
for(int i = 0; i < length; i++){
nums[i] = n%10;
n = n /10;
}
int sum = 0;
for(int i : nums){
sum += i * i;
}
if(set.contains(sum))
return false;
set.add(sum);
return isHappy(sum);
}
}
结果:
这是哪里出了问题呢?
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #87691同步于 2015/8/15
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖
【求助】oj结果与自家编译器结果不一致
rancho
2015/8/15镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
请看这里:
if(set.contains(sum))
return false;
第一次输入10,你返回true
第二次输入10,你返回false
leetcode的测试数据貌似是这个样子: ... 10 ... 10 ...
瞬间懂了,忘记了static的成员变量是对整个类而言的,每一次对象的初始化都保持上一次初始化时的状态。
多谢!
【 在 Insane 的大作中提到: 】
: 请看这里:
: if(set.contains(sum))
: return false;
: ...................
来自「北邮人论坛手机版」
调查一下哈:
1. 你一般一道leetcode题目大概做多久?
2. 提交几种解法?
3. 是否寻找最优解?
4. 是否看Discuss板块?
【 在 rancho 的大作中提到: 】
: 瞬间懂了,忘记了static的成员变量是对整个类而言的,每一次对象的初始化都保持上一次初始化时的状态。
: 多谢!
: 来自「北邮人论坛手机版」
第一个问题:
比较容易上手的话,Easy难度不会超过20min吧,平均也就15分钟。(偶尔还是有逻辑错,可能调起来多花了点时间)
Medium和Hard有些可能会不太熟,半个小时到两个小时都有过。
第二个问题:
有些题目本身的提示会有拓展,比如改进复杂度的要求,如果不是特别难的话,还是会试一试的。
比如我记得有一个Easy的题目,判断一个链表是回文的,提示里问能不能做到O(1)空间复杂度,这个我似乎在AC后做了挺长时间的。
第三、四个问题:
本身我的水平也不高,最优解神马的我也不知道什么样才算。所以每道题还是一定要翻一翻Discuss的,那些浏览和赞同比较多的会点进去看看,看看别人做的是不是有优势,是算法的优势还是语言的优势。
以上,仅供参考。
[ema3]
【 在 Insane 的大作中提到: 】
: 调查一下哈:
: 1. 你一般一道leetcode题目大概做多久?
: 2. 提交几种解法?
: ...................
赞。?。
楼主很棒了。我主要是怕你想我一个师弟,只顾速度,不看质量。他从来不看Discuss。这样效果不好。
楼主的思路不错,顶。学习借鉴了。
再问下:楼主你的代码是放在github上吗?
【 在 rancho 的大作中提到: 】
: 第一个问题:
: 比较容易上手的话,Easy难度不会超过20min吧,平均也就15分钟。(偶尔还是有逻辑错,可能调起来多花了点时间)
: Medium和Hard有些可能会不太熟,半个小时到两个小时都有过。
: ...................
谢谢啦,刚刚我也遇到了这个问题。
【 在 Insane 的大作中提到: 】
: 请看这里:
: if(set.contains(sum))
: return false;
: ...................