Leetcode -- Day 12

Question1

Power of Two

Given an integer, write a function to determine if it is a power of two.

This question is pretty simple. If a number is a power of two, keep it divide by 2, until the result is 1 and the mod of n%2 is always zero.

 1     public boolean isPowerOfTwo(int n) {
 2         if(n<=0)
 3             return false;
 4         while (n>1){
 5             if (n%2 != 0)
 6                 return false;
 7             n = n/2;
 8         }
 9         return true;
10     }

However I read another method using binary bit operation. If a number is power of two, it has only one non-zero number like 1000.

So we can use the & oeprator. This way is very smart and clean.

1     public boolean isPowerOfTwo(int n) {
2         return n > 0 && ((n & (n-1)) == 0);
3     }

Question 2

Pow(x, n)

Implement pow(xn).

One thing you need to notice here is if you continue use result = v * v * v* v....then it will exceed the time limit. So remember to use the n/2. This method will reduce a lot of working time. And be careful to consider the n < 0 case.

 1 public double myPow(double x, int n) {
 2         if (x == 0)
 3             return 0;
 4         if (n == 0)
 5             return 1;
 6
 7         if (n>0)
 8             return power(x,n);
 9         else
10             return 1/power(x,-n);
11
12     }
13
14     public double power(double x, int n){
15
16         if (n == 0)
17             return 1;
18
19         double v = power(x, n/2);
20
21         if (n % 2 == 0)
22             return v*v;
23         else
24             return v*v*x;
25     }

Another method is more clear and shorter, but it use a little trick. It get it 1/x int the very fist time by using half/x*half. For example,

myPow(2, -4) -->

myPow(2, -2) -->

myPow(2, -1)  = 1/2 then back up to

myPow(2, -2) and above it will always call half * half as n % 2 == 0 --> 1/2 * 1/2 * 1/2 * 1/2.

It does not use 1/ total Result but turn each opeartor to 1/half.

public double myPow(double x, int n) {
        if (n == 0) return 1.0;
        double half = myPow(x, n/2);
        if (n%2 == 0)
        {
            return half*half;
        }
        else if (n>0)
        {
            return half*half*x;
        }
        else
        {
            return half/x*half;
        }
    }

Question 3

Valid Number

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

The first direct method is use regular expression, which is cleaner and shorter. But it is not enough for interview. So I do another more complex method.

 1     public boolean isNumber(String s) {
 2         s = s.trim();
 3         if (s.length() == 0)
 4             return false;
 5
 6         String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?";
 7         if (s.matches(regex))
 8             return true;
 9         else
10             return false;
11
12     }

The below one is more complex but much more direct one way.

 1     public boolean isNumber(String s) {
 2         s = s.trim();
 3         int eIndex = -1;
 4         int dotIndex = -1;
 5
 6         if (s.length()==0)
 7             return false;
 8
 9         int i = 0;
10
11         if (s.charAt(i) == ‘+‘ || s.charAt(i) == ‘-‘)
12             s = s.substring(1);
13
14         for (i = 0; i < s.length(); i ++){
15             if (eIndex == -1 && s.charAt(i) == ‘e‘){
16                 eIndex = i;
17                 if (i + 1 < s.length() && (s.charAt(i+1) == ‘-‘ || s.charAt(i+1) == ‘+‘))
18                     i ++;
19             }
20             else if (dotIndex == -1 && s.charAt(i) == ‘.‘)
21                 dotIndex = i;
22             else{
23                 if (Character.isDigit(s.charAt(i)))
24                     continue;
25                 else
26                     return false;
27             }
28         }
29
30         String startString, midString, endString;
31         if (eIndex == -1 && dotIndex == -1){
32             startString = s;
33             if (startString.length() < 1)
34                 return false;
35         }
36         else if (eIndex == -1 && dotIndex != -1){
37             startString = s.substring(0, dotIndex);
38             endString = s.substring(dotIndex+1);
39             if (startString.length()<1 && endString.length() < 1)
40                 return false;
41         }
42         else if (dotIndex == -1 && eIndex != -1){
43             startString = s.substring(0, eIndex);
44             if (startString.length()<1)
45                 return false;
46             if (eIndex+1 < s.length() && (s.charAt(eIndex+1) == ‘+‘ ||s.charAt(eIndex+1) == ‘-‘))
47                 endString = s.substring(eIndex + 2);
48             else
49                 endString = s.substring(eIndex + 1);
50             if (endString.length()<1)
51                 return false;
52         }
53         else{
54             if (dotIndex > eIndex)  return false;
55             else{
56                 startString = s.substring(0, dotIndex);
57                 midString = s.substring(dotIndex+1, eIndex);
58                 if (startString.length()<1 && midString.length()<1)
59                     return false;
60                 if (eIndex+1 < s.length() && (s.charAt(eIndex+1) == ‘+‘ ||s.charAt(eIndex+1) == ‘-‘))
61                     endString = s.substring(eIndex + 2);
62                 else
63                     endString = s.substring(eIndex + 1);
64                 if (endString.length()<1 )
65                     return false;
66             }
67         }
68         return true;
69     }

Question 4

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

Very clever is to use binary search. There are some tricks here:

1. r = x/2 + 1; the square root must lest than the n/2 +1; So we can ignore some number for checking.

2. use x/m<m rather thatn x < m*m, which may exceed the MAX_VALUE  or time limit.

 1 public int mySqrt(int x) {
 2         if(x<0) return -1;
 3         if(x==0) return 0;
 4         int l=1;
 5         int r=x/2+1;
 6         while(l<=r)
 7         {
 8             int m = (l+r)/2;
 9             if(m<=x/m && x/(m+1)<m+1)
10                 return m;
11             if(x/m<m)
12             {
13                 r = m-1;
14             }
15             else
16             {
17                 l = m+1;
18             }
19         }
20         return 0;
21 }
时间: 2024-10-19 03:00:14

Leetcode -- Day 12的相关文章

【leetcode】12. Integer to Roman

题目描述: Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 解题思路: 注意到用例比较少,所以采用以空间换时间的方法,把所有的结果列出,然后组合出输入值n的字符串即可. 具体代码: 1 public class Solution { 2 public static String intToRoman(int num) { 3 St

LeetCode第12题 整数转罗马数字

/* 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为两个并列的 1.12 写做 XII ,即为 X + II . 27 写做 XXVII, 即为 XX + V + II . 通常情况下,罗马数字中小的数字在大的数字的右边. 但也存在特例,例如 4 不写做 IIII,而是 IV.数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数

LeetCode(12)Integer to Roman

题目 Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 分析 该题目要求将给定的1~3999之间的整型数字转换为罗马数字并输出. 解这道题我们必须了解罗马字母与整数之间的对应: 对照举例如下: AC代码 class Solution { public: string intToRoman(int num) { //存储罗马数字 st

leetcode第12题--Integer to Roman

Problem: Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 把阿拉伯数字转换为罗马数字输出.百度一下对应的 I V X L C D M,代表1,5,10,50,100,500,1000 然后写一个子函数,输入数字和相应的位数级别,如个位为level 1,千为4.因为最多不会超过四千.所以可以如下.注意了,string用法很好

Cipe Coding Summary Part1

1. Colorful Number:A numbercan be broken into different sub-sequence parts. Suppose a number 3245 can bebroken into parts like 3 2 4 5 32 24 45 324 245. And this number is a colorfulnumber, since product of every digit of a sub-sequence are different

vc编程中的20点小笔记

机器学习是一项经验技能,经验越多越好.在项目建立的过程中,实践是掌握机器学习的最佳手段.在实践过程中,通过实际操作加深对分类和回归问题的每一个步骤的理解,达到学习机器学习的目的. 预测模型项目模板不能只通过阅读来掌握机器学习的技能,需要进行大量的练习.本文将介绍一个通用的机器学习的项目模板,创建这个模板总共有六个步骤.通过本文将学到: 端到端地预测(分类与回归)模型的项目结构. 如何将前面学到的内容引入到项目中. 如何通过这个项目模板来得到一个高准确度的模板. 副诼匚盼胁臼匾膊讶赖期放判鼻懒合谖

[LeetCode] Palindrome Partitioning II [12]

题目 Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = "aab", Return 1 since the palindrome partitioning ["aa&qu

[LeetCode] 12. Integer to Roman ☆☆

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 解释: 罗马数字采用七个罗马字母作数字.即Ⅰ(1).X(10).C(100).M(1000).V(5).L(50).D(500).记数的方法: 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3: 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8.

LeetCode 12 Integer to Roman (整数转罗马数字)

题目链接: https://leetcode.com/problems/integer-to-roman/?tab=Description String M[] = {"", "M", "MM", "MMM”};//1000~3000String C[] = {"", "C", "CC", "CCC", "CD", "D&quo