BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #43545同步于 2015/8/15
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

[已解决]oj的java执行机制问题?

rancho
2015/8/15镜像同步5 回复
在别人的帮助下,发现原因很简单: java中static修饰的成员是属于整个类的,每一次对象的初始化,都保持上一次初始化的值不变。也就是说之前的测例中出现过10或者1在HashSet中存在。 自己的myeclipse与leetcode上相同代码,结果有出入。 题目是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); } } 结果: 这是哪里出了问题呢?
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
icyfox机器人#1 · 2015/8/15
可是你Eclipse 里的代码和leetcode里的代码明明不一样啊 function的static呢?
rancho机器人#2 · 2015/8/15
多谢,在ACM版已解决。 (话说在一个类里面main函数是static的话,是不能调用不是static是成员函数的...只能这么写,,) 【 在 icyfox 的大作中提到: 】 : 可是你Eclipse 里的代码和leetcode里的代码明明不一样啊 function的static呢?
icyfox机器人#3 · 2015/8/15
所以最终就是static的错啊 所以最终你的代码就是不一样对不对? static的特性谁都明白,你这个代码还能缩一半 【 在 rancho (rancho||水央月) 的大作中提到: 】 : 多谢,在ACM版已解决。 : (话说在一个类里面main函数是static的话,是不能调用不是static是成员函数的...只能这么写,,)
rancho机器人#4 · 2015/8/15
求问怎么缩? 是利用这个特性将所有的检测过true的数放在一个HashSet里面是吗?如果递归的过程中碰到了直接返回true? 【 在 icyfox 的大作中提到: 】 : 所以最终就是static的错啊 : 所以最终你的代码就是不一样对不对? : static的特性谁都明白,你这个代码还能缩一半 : ...................
icyfox机器人#5 · 2015/8/15
首先,不需要用integer声明 其次,不需要使用数组存储每个位数的值 最后,用循环就够了 【 在 rancho 的大作中提到: 】 : 求问怎么缩? : 是利用这个特性将所有的检测过true的数放在一个HashSet里面是吗?如果递归的过程中碰到了直接返回true? 来自「北邮人论坛手机版」