1. 程式人生 > >兩道筆試題

兩道筆試題

write keys include key des until class eof n)

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^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1 ======================== public class Solution { private static int maxTimes = 100; public boolean isHappy(int n, int times) { String sn
= String.valueOf(n); int ss = sn.length(); int sum = 0; if(times >= Solution.maxTimes){ return false; } for(int i=0;i<ss-1; i++){ int y = n % Math.pow(10, ss-i); int z = y / Math.pow(10, i+1); sum += Math.pow(z, 2); }
if(sum == 1) return true; times++; isHappy(sum, times); } } ------------------------------------- Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node‘s key. The right subtree of a node contains only nodes with keys greater than the node‘s key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / 1 3 Binary tree [2,1,3], return true. Example 2: 1 / 2 3 Binary tree [1,2,3], return false. ===================================== /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { if(root == null) return false; if(root.left != null){ if(root.left.val >= root.val)return false; } if(root.left.right != null){ if(root.left.right.val >= root.val)return false; } if(root.right != null){ if(root.right.val <= root.val)return false; } if(root.right.left != null){ if(root.right.left.val <= root.val)return false; } if(root.left != null) isValidBST(root.left); if(root.right != null) isValidBST(root.right); return true; } }

兩道筆試題