zoukankan      html  css  js  c++  java
  • Leetcode 7

    Math Easy

    1.7. Reverse Integer

      采用验证的方式,如果当前newResult越界,返回错误。

     1 class Solution {
     2     public int reverse(int x) {
     3         int res = 0;
     4         int tail = 0;
     5     
     6         while( x != 0){
     7             int newResult = 0;
     8             tail = x % 10;
     9             newResult = res*10 + tail;
    10             if((newResult - tail) / 10 != res)
    11                 return 0;
    12             res = newResult;
    13             x /= 10;
    14         }
    15         return res;
    16     }
    17 }

    2. 9. Palindrome Number

      我们可以利用取整和取余来获得我们想要的数字,比如 1221 这个数字,如果 计算 1221 / 1000, 则可得首位1, 如果 1221 % 10, 则可得到末尾1,进行比较,然后把中间的22取出继续比较。

     1 class Solution {
     2     public boolean isPalindrome(int x) {
     3         if( x < 0)
     4             return false;
     5         int div = 1;
     6         while(x/div >= 10) div *= 10;
     7         while(x > 0){
     8             int left = x/div;
     9             int right = x%10;
    10             if(left != right)
    11                 return false;
    12             x = (x % div) /10;
    13             div /= 100;
    14         }
    15         return true;
    16     }
    17 }

    3. 13. Roman to Integer

      我们需要用到HashMap数据结构,来将罗马数字的字母转化为对应的整数值,因为输入的一定是罗马数字,那么我们只要考虑两种情况即可:

      第一,如果当前数字是最后一个数字,或者之后的数字比它小的话,则加上当前数字。
      第二,其他情况则减去这个数字。
     1 class Solution {
     2     public int romanToInt(String s) {
     3         int res = 0;
     4         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
     5         map.put('I',1);
     6         map.put('V',5);
     7         map.put('X',10);
     8         map.put('L',50);
     9         map.put('C',100);
    10         map.put('D',500);
    11         map.put('M',1000);
    12         
    13         for(int i = 0; i <s.length(); i++){
    14             int val = map.get(s.charAt(i));
    15             if( i == s.length()-1 || map.get(s.charAt(i+1)) <= map.get(s.charAt(i)))
    16                 res += val;
    17             else
    18                 res -= val;
    19         }
    20         return res;
    21     }
    22 }
  • 相关阅读:
    Hash表的查找-C语言
    二叉排序树-C语言
    线性表的查找算法-C语言
    拓扑排序和关键路径
    图结构的创建与遍历-C语言
    MySQL数据库基本脚本命令
    哈夫曼树编码-C语言
    协程简述
    Python多线程编程-Threading库
    Python多进程编程-multiprocessing库
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/10758083.html
Copyright © 2011-2022 走看看