Math DayTwo

时间:2023-12-19 23:41:56

(1)Excel Sheet Column Number

Math DayTwo

解题思路:将26进制的数转化为10进制

代码如下:

 public class Solution {
public int titleToNumber(String s) {
return s.length() == 0 ? 0 : (s.charAt(s.length() - 1)-'A' + 1) + 26 * titleToNumber(s.substring(0 , s.length() - 1));
}
}

(2)Roman to Integer

Math DayTwo

解题思路:

Math DayTwo

使用HashMap存入7个罗马字母和相对应的整数,然后从最低位(最右)开始依次跟相邻高位作比较,低位数字小的话就相加,低位数字大的话就相减。

代码如下;

 public class Solution {
public int romanToInt(String s) {
if (s == null || s.length()==0) {
return 0;
}
Map<Character, Integer> m = new HashMap<Character, Integer>();
m.put('I', 1);
m.put('V', 5);
m.put('X', 10);
m.put('L', 50);
m.put('C', 100);
m.put('D', 500);
m.put('M', 1000); int length = s.length();
int result = m.get(s.charAt(length - 1));
for (int i = length - 2; i >= 0; i--) {
if (m.get(s.charAt(i + 1)) <= m.get(s.charAt(i))) {//小的数字在大的数字右边
result += m.get(s.charAt(i));
} else {
result -= m.get(s.charAt(i));//小的数字在大的数字左边
}
}
return result;
}
}

(3) Add Strings

Math DayTwo

代码如下:

 public class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int carry = 0;//进位
for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){
int x = i < 0 ? 0 : num1.charAt(i) - '0';
int y = j < 0 ? 0 : num2.charAt(j) - '0';
sb.append((x + y + carry) % 10);
carry = (x + y + carry) / 10;
}
return sb.reverse().toString();
}
}

解题思路:

使用Java中的StringBuilder类新建一个对象sb,用carry表示进位值。两个字符串同时从最低位(最右)字符开始相加,sb中添加x+y+carry%10的余数,carry更新为新的进位值,直至所有数字都相加而且进位为0时将字符串sb反转返回即可。

(4)Power of Three

Math DayTwo

解题思路:

假设一个数Num是3的幂,那么所有Num的约数都是3的幂,如果一个数n小于Num且是3的幂,那么这个数n一定是Num的约数。

了解上述性质,我们只需要找到一个最大的3的幂,看看参数n是不是此最大的幂的约数就可以。

代码如下:

 public class Solution {
public boolean isPowerOfThree(int n) {
// 1162261467 is 3^19, 3^20 is bigger than int
return (n > 0 && 1162261467 % n == 0);
}
}

(5)Power of Two

Math DayTwo

解题思路:

Math DayTwo

代码如下:

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

(6)Ugly Number

Math DayTwo

解题思路:

num被2,3,5整除之后判断商是否等于1,不等于1说明有别的除数,不是uglynumber。

代码一如下:

 public class Solution {
public boolean isUgly(int num) {
//不会用到4 ,因为4是2的2倍。
for (int i = 2; i < 6 && num > 0; i++) {
while (num % i == 0) {
num /= i;
}
}
return num == 1;
}
}

代码二如下:

 public class Solution {
/**
* @param num an integer
* @return true if num is an ugly number or false
*/
public boolean isUgly(int num) {
if (num <= 0) return false;
if (num == 1) return true; while (num >= 2 && num % 2 == 0) num /= 2;
while (num >= 3 && num % 3 == 0) num /= 3;
while (num >= 5 && num % 5 == 0) num /= 5; return num == 1;
}
}