• 1LL(1ll) 与 std::to_string()


    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            return dfs(root, INT_MIN, INT_MAX);
        }
     
        bool dfs(TreeNode *root, long long minv, long long maxv){
        	if(!root) return true;
        	if(root -> val < minv || root -> val > maxv) return false;
     
        	return dfs(root -> left, minv, root -> val -1ll) && dfs(root -> right, root -> val + 1ll, maxv);
        }
    };
    

    1LL是long long 类型的1,一个int 型的数和一个long long 型的数做运算返回值是long long 类型的,利用这种方式来防止溢出。

    std::to_string() 是c++11引入的函数,其使用方法如下:

    string to_string (int val);
    string to_string (long val);
    string to_string (long long val);
    string to_string (unsigned val);
    string to_string (unsigned long val);
    string to_string (unsigned long long val);
    string to_string (float val);
    string to_string (double val);
    string to_string (long double val);
    

    样例如下:

    // to_string example
    #include <iostream>   // std::cout
    #include <string>     // std::string, std::to_string
     
    int main ()
    {
      std::string pi = "pi is " + std::to_string(3.1415926);
      std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
      std::cout << pi << '\n';
      std::cout << perfect << '\n';
      return 0;
    }
    

    Output:

    pi is 3.141593
    28 is a perfect number
    

    std::to_string()无法控制生成字符串的格式,意味着你会遇见这样的情况:

    std::cout << std::to_string(0.33) << std::endl;
    0.330000
    
  • 相关阅读:
    《JavaScript高级程序设计》第14、17、20章
    《JavaScript高级程序设计》第12-13章
    《JavaScript高级程序设计》第10-11章
    《JavaScript高级程序设计》第8-9章
    《JavaScript高级程序设计》第6-7章
    《JavaScript高级程序设计》第4-5章
    《JavaScript高级程序设计》第1-3章
    《CSS3秘籍》第12-17章
    《CSS3秘籍》第8-11章
    jsoncpp操作 json
  • 原文地址:https://www.cnblogs.com/lihello/p/11520939.html
Copyright © 2020-2023  润新知