zoukankan      html  css  js  c++  java
  • leetcode 166

    我的想法很简单, 先存一下符号, 然后从小数第一位开始进行记录, 每次都乘10 相除, 直到遇到重复的, 为了防止溢出用了long long

    class Solution {
    public:
        string fractionToDecimal(int numerator, int denominator) {
            if (0 == numerator){
                return "0";
            }
            long long num = numerator, den = denominator, tmp;
            // map<long long, int> num_map;
            set<long long> num_set;
            vector<long long> result_int, tmp_list;
            string result = "";
            bool postive = false;
            // int i = 0;
            if ((num < 0 and den < 0) or (num > 0 and den > 0)){
                postive = true;
            }else {
                postive = false;
            }
            if (false == postive){
                result.append("-");
            }
            if (num < 0){
                num = -1 * num;
            }
            if (den < 0){
                den = -1 * den;
            }
    
            // result_int.push_back(num / den);
            result.append(to_string(num / den));
    
            tmp = num % den;
            if (0 == tmp){
                return result;
            }
            result.append(".");
    
            while (0 != tmp){
                tmp *= 10;
                if (num_set.find(tmp) != num_set.end()){
                    break;
                }
                num_set.insert(tmp);
                result_int.push_back(tmp / den);
                tmp_list.push_back(tmp);
                tmp = tmp % den;
            }
    
            if (0 == tmp){
                for (vector<long long>::iterator i = result_int.begin(); i != result_int.end(); i++){
                    result.append(to_string(*i));
                }
            }else{
                for(int i = 0; i < result_int.size(); i++){
                    
                    if (tmp == tmp_list[i]){
                        result.append("(");
                    }
                    result.append(to_string(result_int[i]));
                }
                result.append(")");
            }
            return result;
    
        }
    };
    
  • 相关阅读:
    Dex-Net笔记
    python笔记
    linux和anaconda
    JPA和Hibernate的关系
    eclipse利用JPA,根据数据库表生成Java中的实体类
    eclipse中利用hibernate插件,根据数据库表反向生成Javabean
    eclipse中git常用操作说明
    oracle常用语法
    threadlocal
    spring用到的一些注解小札
  • 原文地址:https://www.cnblogs.com/mangmangbiluo/p/15635707.html
Copyright © 2011-2022 走看看