- Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range:−2^31 ~ 2^31 − 1.
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
/**
* 为了不溢出,res设为long的神奇算法,有人点评用long是作弊...?
* 3 ms 38.2 MB
*/
class Solution1 {
public int reverse(int x) {
long res = 0;
while(x!=0){
res = res*10+x%10;
x/=10;
}
if(res<Integer.MIN_VALUE || res>Integer.MAX_VALUE){
return 0;
}else{
return (int) res;
}
}
}
/**
* 用StringBuilder自带reverse功能的算法
* 5 ms 38.5 MB
*/
class Solution {
public int reverse(int x) {
StringBuilder sb = new StringBuilder();
boolean isNegative = false;
if(x<0){
x=-x;
isNegative=true;
}
sb.append(x);
sb.reverse();
if(isNegative){
sb.insert(0,'-');
}
int res;
try{
res=Integer.valueOf(sb.toString()); //valueOf,return Integer object
}catch(Exception e){
return 0;
}
return res;
}
}
/**
* StringBuilder加强版写法
* 2 ms 36.5 MB
*/
class Solution {
public int reverse(int x) {
String reversed = new StringBuilder().append(Math.abs(x)).reverse().toString();
try {
return (x < 0) ? Integer.parseInt(reversed) * -1 : Integer.parseInt(reversed);
} catch (NumberFormatException e) {
return 0;
}
}
}
- Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
Example 1:
Input: x = 121 Output: true
Example 2:
Input: x = -121 Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10 Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
/**
* 直白算法就是把x一位一位反着排出来与原数比较,复杂度比较高。特殊情况在第一行处理了。
* 10 ms 41.1 MB
*/
class Solution1 {
public boolean isPalindrome(int x) {
if(x<0 || (x%10==0&& x!=0)){return false;}
int reverse = 0;
int origin = x;
while(x!=0){
reverse = reverse*10+x%10;
x/=10;
}
if(reverse==origin){return true;}
else{return false;}
}
}
/**
* 根据回文数的特点,判断左边一半和翻转后的右边一半是否相等,奇数位x的话得到的reverse会多一位喔
* 6 ms 38.1 MB 复杂度比较理想
*/
class Solution2 {
public boolean isPalindrome(int x) {
if(x<0 || (x%10==0&& x!=0)){return false;}
int reverse = 0;
while(x>reverse){
reverse = reverse*10+x%10;
x = (int) x/10;
}
return x==reverse||x==(int)reverse/10;
}
}
- Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII
, which is simply X + II
. The number 27 is written as XXVII
, which is XX + V + II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Example 2:
Input: s = "IV"
Output: 4
Example 3:
Input: s = "IX"
Output: 9
Example 4:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters (‘I’, ‘V’, ‘X’, ‘L’, ‘C’, ‘D’, ‘M’).
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
/**
* 用两个指针记录,前>后加上,前<后得把之前加上的前前去,所以是-2*cur。用Map记录映射速度比较慢。
* 9 ms 43.2 MB
*/
class Solution {
public int romanToInt(String s) {
Map<Character,Integer> map = new HashMap<>(){{
put('I',1);
put('V',5);
put('X',10);
put('L',50);
put('C',100);
put('D',500);
put('M',1000);
}};
int pre=0,cur=0,sum=0;
for(int i=0;i<s.length();i++){
cur=map.get(s.charAt(i));
if(pre>=cur){
sum+=cur;
}else{
sum+=cur-2*pre;
}
pre=cur;
}
return sum;
}
}
/**
* 主题思路不变,用switch来判断映射快很多。 3 ms 39.3 MB
*/
class Solution {
public int romanToInt(String s) {
int pre=0,cur=0,sum=0;
for(int i=0;i<s.length();i++){
cur=charToInt(s.charAt(i));
if(pre>=cur){
sum+=cur;
}else{
sum+=cur-2*pre;
}
pre=cur;
}
return sum;
}
private int charToInt(char c){
switch(c){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
}
- Pow(x, n)- 扩展包Medium
比如说 2 的 9 次方, 那么 2^9 = 2^4 * 2^4 * 2 = 2 ^2 * 2^2 * 2^2 * 2^2 * 2 = 2 ^1 * 2^1 * (总共八个2^1) * 2
如果是负次方,则计算正次方之后被 1 除一下。
class Solution {
public double myPow(double x, int n) {
return n>=0? powerHelper(x,n) : 1/powerHelper(x,-n);
}
private double powerHelper(double x, int n){
if(n==0){return 1.0;}
double res=powerHelper(x,n/2);
return n%2==0? res*res : res*res*x;
}
}
时间跑出来不如用语法糖。。。
return Math.pow(x,n);
- Plus One
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
class Solution {
public int[] plusOne(int[] digits) {
int carry =1;
for(int i=digits.length-1;i>=0;i--){
if(digits[i]<9){
digits[i]+=carry;
return digits;
}else{
digits[i]=0;
}
}
int[] res = new int[digits.length+1];
res[0]=1;
return res;
}
}
- Add Binary
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = “11”, b = “1”
Output: “100”
/**
* 从右到左每一位相加,用stringBuilder记录,别忘最后reverse 3 ms 37.4 MB
* /
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int lenA=a.length()-1;
int lenB=b.length()-1;
int carry = 0;
while(lenA>=0||lenB>=0){
int da = lenA>=0? a.charAt(lenA)-'0' : 0;
int db = lenB>=0? b.charAt(lenB)-'0' : 0;
int sum = da+db+carry;
if(sum==3){
sb.append(1);
carry=1;
}else if(sum==2){
sb.append(0);
carry=1;
}else{
sb.append(sum);
carry=0;
}
lenA--;
lenB--;
}
if(carry==1){
sb.append(1);
}
return sb.reverse().toString();
}
}
- Sqrt(x)
直接用语法糖速度和二分法差不多
return (int)Math.sqrt(x);
class Solution {
public int mySqrt(int x) {
if(x<=1){return x;}
int left=1,right=x,res=-1;
while(left<=right){
int mid=left+(right-left)/2;
if((long)mid*mid<=x){
res=mid;
left=mid+1;
}else{
right=mid-1;
}
}
return res;
}
}
- Count Primes
Count the number of prime numbers less than a non-negative number, n.
Example 1:
Input: n = 10 Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
/**
* 直白算法会超时,过不了速度测试T.T
*/
class Solution {
public int countPrimes(int n) {
int count=0;
for(int i=2;i<n;i++){
if(isPrime(i)){count++;}
}
return count;
}
private boolean isPrime(int x){
for(int i=2;i*i<=x;i++){
if(x%i==0){
return false;
}
}
return true;
}
}
/**
* 厄拉多塞筛法--当遍历到一个数时,把这个数的倍数全部剔除掉,因为他们不可能为质数,最终没有被剔除的数就是质数
* 用notPrime数组记录遍历2-sqrt(n),如果当前是质数,他的倍数设true(不为质数),最后统计false个数,为质数个数。
* 16 ms 37 MB
*/
class Solution {
public int countPrimes(int n) {
if(n <=1 ) return 0;
boolean[] notPrime = new boolean[n];
notPrime[0]=true;
notPrime[1]=true;
for(int i=2;i<Math.sqrt(n);i++){
if(!notPrime[i]){
for(int j=2;i*j<n;j++){
notPrime[i*j]=true;
}
}
}
int count=0;
for(boolean b : notPrime){
count += b? 0 : 1;
}
return count;
}
}