GVKun编程网logo

[Algorithm] Convert a number from decimal to binary

13

如果您对[Algorithm]Convertanumberfromdecimaltobinary感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解[Algorithm]Convertanumber

如果您对[Algorithm] Convert a number from decimal to binary感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解[Algorithm] Convert a number from decimal to binary的各种细节,此外还有关于"from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"、177. Convert Sorted Array to Binary Search Tree With Minimal Height【LintCode by java】、2D Convex Hulls and Extreme Points( Convex Hull Algorithms) CGAL 4.13 -User Manual、405. Convert a Number to Hexadecimal的实用技巧。

本文目录一览:

[Algorithm] Convert a number from decimal to binary

[Algorithm] Convert a number from decimal to binary

125,how to conver to binary number?

分享图片

 

function DecimalToDinary (n) {
  let temp = n;
  let list = [];

  if (temp <= 0) {
    return ‘0000‘;
  }

  while (temp > 0) {
    let rem = temp % 2;
    list.push(rem);
    temp = parseInt(temp / 2,10);
  }

  return list.reverse().join(‘‘);
}

console.log(DecimalToDinary(125)) // 1111101

"from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"

I created the /var/www/cgi-bin/test.py in my web server machine (Linux). The service of mongoDB "mongod" is running.

When I run the test.py locally, "./test.py", I could get the correct result.

But when I use the URL: http://xxxxxx.compute-1.amazonaws.com/cgi-bin/python_test/test.py to run the test.py, I will get the "500 Internal Server Error". 

If I remove the line "from pymongo import Connection", and use the URL above to access, I won''t get the 500 Internal server error. So, it should be the problem when I import the pymongo.connection.

Is it the problem of any configuration issue? Thanks so much for your help

========== test.py ==============

#!/usr/bin/python
import cgi
import sys
sys.path.append("/home/ec2-user/mongo-python-driver-2.6.3/")

#import pymongo.connection
from pymongo import Connection
def main():
        print "Content-type: text/html\r\n\r\n"
        form = cgi.FieldStorage()
        name = form.getvalue(''ServiceCode'')
#       name = "abcddd"
#       con = Connection()
#       db = con.test
#       posts = db.post

#       print name
        if form.has_key("ServiceCode") and form["ServiceCode"].value!="":
                print"<h1>Hello", form["ServiceCode"].value,"</h1>"
        else:
                print"<h1>Error! Please enter first name. </h1>"

 .....


177. Convert Sorted Array to Binary Search Tree With Minimal Height【LintCode by java】

Description

Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.

There may exist multiple valid solutions, return any of them.

Example

Given [1,2,3,4,5,6,7], return

     4
   /   \
  2     6
 / \    / \
1   3  5   7

解题:题目要求根据一个有序的数组创建一个二叉排序树,并且返回这个排序树。要求高度最小,那么必定是平衡二叉树,每次取有序序列最中间的那个数作为结点即可。递归方法,代码如下:

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param A: an integer array
17      * @return: A tree node
18      */
19     public TreeNode sortedArrayToBST(int[] A) {
20         // write your code here
21         return create(A, 0, A.length - 1);
22     }
23     private TreeNode create(int[]A, int first, int last){
24         if(first >last)
25            return null;
26         int mid = (first + last) / 2;
27         TreeNode node = new TreeNode( A[mid] );
28         node.left = create(A, first, mid-1);
29         node.right = create(A, mid+1, last);
30         return node;
31     }
32 }

 

2D Convex Hulls and Extreme Points( Convex Hull Algorithms) CGAL 4.13 -User Manual

2D Convex Hulls and Extreme Points( Convex Hull Algorithms) CGAL 4.13 -User Manual

1 Introduction

A subset SR2 is convex if for any two points p and q in the set the line segment with endpoints p and q is contained in S. The convex hull of a set S is the smallest convex set containing S. The convex hull of a set of points P is a convex polygon with vertices in P. A point in P is an extreme point (with respect to P) if it is a vertex of the convex hull of P. A set of points is said to be strongly convex if it consists of only extreme points.

This chapter describes the functions provided in CGAL for producing convex hulls in two dimensions as well as functions for checking if sets of points are strongly convex are not. There are also a number of functions described for computing particular extreme points and subsequences of hull points, such as the lower and upper hull of a set of points.

 一个点集 SR2,如果对于点集中任意两个点 p 和 q ,以 p 和 q 为端点的线段被包在这个子集 (构成的多边形) 中,我们称 S 是凸的(convex )。一个点集 S 的凸包(convex hull )是包含 S 的最小凸集。一个点集 P 的凸包(convex hull )是一个以 P 中的点为顶点的多项式。如果 P 中一个点是其凸包(convex hull )中的一个顶点,则该点是一个 P 的极点(extreme point )。一个点集被称为强凸的(strongly convex )如果它只包含极点。

本章描述 CGAL 提供的在 2 维中生成凸包(convex hulls)的函数和用于检查点集是否强凸的(strongly convex )的函数。还有一些函数用于计算特定极点以及包(hull)生成之后的其他函数,如点集的下半包和上半包。

saarhull.png

2 Convex Hull

CGAL provides implementations of several classical algorithms for computing the counterclockwise sequence of extreme points for a set of points in two dimensions (i.e., the counterclockwise sequence of points on the convex hull). The algorithms have different asymptotic running times and require slightly different sets of geometric primitives. Thus you may choose the algorithm that best fits your setting.

Each of the convex hull functions presents the same interface to the user. That is, the user provides a pair of iterators, first and beyond, an output iterator result, and a traits class traits. The points in the range [firstbeyond) define the input points whose convex hull is to be computed. The counterclockwise sequence of extreme points is written to the sequence starting at position result, and the past-the-end iterator for the resulting set of points is returned. The traits classes for the functions specify the types of the input points and the geometric primitives that are required by the algorithms. All functions provide an interface in which this class need not be specified and defaults to types and operations defined in the kernel in which the input point type is defined.

Given a sequence of n input points with h extreme points, the function convex_hull_2() uses either the output-sensitive O(nh) algorithm of Bykat [5] (a non-recursive version of the quickhull [4] algorithm) or the algorithm of Akl and Toussaint, which requires O(nlogn) time in the worst case. The algorithm chosen depends on the kind of iterator used to specify the input points. These two algorithms are also available via the functions ch_bykat() and ch_akl_toussaint(), respectively. Also available are the O(nlogn) Graham-Andrew scan algorithm [3], [9] (ch_graham_andrew()), the O(nh) Jarvis march algorithm [8] (ch_jarvis()), and Eddy''s O(nh)algorithm [6] (ch_eddy()), which corresponds to the two-dimensional version of the quickhull algorithm. The linear-time algorithm of Melkman for producing the convex hull of simple polygonal chains (or polygons) is available through the function ch_melkman().

CGAL 提供了 2d 空间中的几种典型的算法来计算逆时针序的极点集(即凸包的逆时针序的点集)。各个算法有着不同的渐近线时间效率,需要稍有不同的几何元语集合。这样你可以选择最适合你的算法。

每个计算凸包的函数提供了相同的接口。用户提供一对 iterator , first 和 beyond,一个输出 iterator result, 和一个 traits 类 traits。在范围 [firstbeyond) 的点用于定义输入的需要计算其凸饭点集。逆时针序的极点集被写入了始于 result 的序列中,且最后一个点的(past-the-end)iterator 被 返回。traits 类用于确定输入点的数的类型和算法所要求的几何元语集合。所有的函数提供了一个接口,使用这个接口时这个类不需要指定,输入点的缺省类型(All functions provide an interface in which this class need not be specified and defaults to types and operations defined in the kernel in which the input point type is defined)。

给定 n 个输入点的序列,其中有 h 个极点,

(1)Bykat 算法(output-sensitive O(nh) algorithm of Bykat, 一种 quickhull 算法的非回归版本),

(2)Akl 和 Toussaint 算法,它们最差的情况下需要 O(nlogn) 时间。算法的选择依赖于指定的输入点集。这两个算法也可以通过 ch_bykat() 和 ch_akl_toussaint()函数分别得到。

(3)Graham-Andrew 扫描算法(Graham-Andrew scan algorithm , (ch_graham_andrew()),)其算法时间为 O(nlogn) 。

(4)Jarvis march 算法(Jarvis march algorithm,  (ch_jarvis()), O(nh)

(5)Eddy'' 算法(Eddy''s O(nh)algorithm,ch_eddy()),它对应于 quickhull 算法的 2 维版本。

(6)Melkman 算法提供线性时间,为简单多边形链计算凸包(函数 ch_melkman())

3 Example using Graham-Andrew''s Algorithm

In the following example a convex hull is constructed from point data read from standard input using Graham_Andrew algorithm. The resulting convex polygon is shown at the standard output console. The same results could be achieved by substituting the function ch_graham_andrew() by other functions such as ch_bykat().

下面的例子使用标准输入点数据生成凸包,使用 ch_graham_andrew() 算法。其结果凸多边形输出到标准输出窗口。换函数 ch_bykat() 可得到相同结果。
File Convex_hull_2/ch_from_cin_to_cout.cpp

#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/ch_graham_andrew.h>
 
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_2 Point_2;
 
int main()
{
CGAL::set_ascii_mode(std::cin);
CGAL::set_ascii_mode(std::cout);
std::istream_iterator< Point_2 > in_start( std::cin );
std::istream_iterator< Point_2 > in_end;
std::ostream_iterator< Point_2 > out( std::cout, "\n" );
CGAL::ch_graham_andrew( in_start, in_end, out );
return 0;
}

4 Extreme Points and Hull Subsequences

In addition to the functions for producing convex hulls, there are a number of functions for computing sets and sequences of points related to the convex hull.

The functions lower_hull_points_2() and upper_hull_points_2() provide the computation of the counterclockwise sequence of extreme points on the lower hull and upper hull, respectively. The algorithm used in these functions is Andrew''s variant of Graham''s scan algorithm [3], [9], which has worst-case running time of O(nlogn).

There are also functions available for computing certain subsequences of the sequence of extreme points on the convex hull. The function ch_jarvis_march() generates the counterclockwise ordered subsequence of extreme points between a given pair of points and ch_graham_andrew_scan() computes the sorted sequence of extreme points that are not left of the line defined by the first and last input points.

Finally, a set of functions (ch_nswe_point()ch_ns_point()ch_we_point()ch_n_point()ch_s_point()ch_w_point()ch_e_point()) is provided for computing extreme points of a 2D point set in the coordinate directions.

另外,还有一些函数用于与凸包相关的点集计算。

(1)lower_hull_points_2() 和 upper_hull_points_2()用于计算逆时针序的下半包和上半包。这个算法是 Graham''s scan algorithm 的 Andrew'' 变种,最差为 O(nlogn);

(2)还有一些函数用于计算已经生成的凸包中的极点的子序列(subsequence )的函数。ch_jarvis_march() 用于计算给定两点之间的逆时针序的极点的子序列,ch_graham_andrew_scan() 用于生成一个逆时针排列的极点的子序列,这个子序列的所有极点均不在给定输入点的左侧。(computes the sorted sequence of extreme points that are not left of the line defined by the first and last input points.)

(3)最后,一个函数集用于计算给定坐标方向 ( coordinate directions) 的极点集(ch_nswe_point()ch_ns_point()ch_we_point()ch_n_point()ch_s_point()ch_w_point()ch_e_point()).

5 Traits Classes

Each of the functions used to compute convex hulls or extreme points is parameterized by a traits class, which specifies the types and geometric primitives to be used in the computation. There are several implementations of 2D traits classes provided in the library. The class Convex_hull_traits_2 corresponds to the default traits class that provides the types and predicates presented in the 2-dimensional CGAL kernel in which the input points lie. The class Convex_hull_constructive_traits_2 is a second traits class based on CGAL primitives but differs from Convex_hull_traits_2 in that some of its primitives reuse intermediate results to speed up computation.

In addition, the 2D and 3D Linear Geometric Kernel provides three projective traits classes (Projection_traits_xy_3Projection_traits_xz_3, and Projection_traits_yz_3), which may be used to compute the convex hull of a set of three-dimensional points projected into each of the three coordinate planes.

每个计算凸包或极点的函数都被一个 traits 类参数化,这个 traits 指定了计算中使用的类型和几何元语。库中有几个 2D traits 类。

(1)Convex_hull_traits_2 类对应于 2D CGAL 内核中缺省的 traits 类,提供了类型和判定(The class Convex_hull_traits_2 corresponds to the default traits class that provides the types and predicates presented in the 2-dimensional CGAL kernel in which the input points lie. )。

(2)Convex_hull_constructive_traits_2 类是第二个基于 CGAL 元语的 traits 类,与 Convex_hull_traits_2不同的是,它的元语复用了中间结果来加速计算。

(3)另外, 2D 和 3D Linear Geometric Kernel 提供了三个投射 traits 类(projective traits classes ), 分别是 Projection_traits_xy_3Projection_traits_xz_3, 的 Projection_traits_yz_3,用于计算3维点投射到三个坐标平面的点集的凸包。

6 Convexity Checking

The functions is_ccw_strongly_convex_2() and is_cw_strongly_convex_2() check whether a given sequence of 2D points forms a (counter)clockwise strongly convex polygon. These are used in postcondition testing of the two-dimensional convex hull functions.

函数 is_ccw_strongly_convex_2() 和 is_cw_strongly_convex_2() 检查给定一个序列的 2D 点集是否形成一个(顺)逆时针的强凸多边形。这些函数用于对 2 维凸包函数的后置条件进行测试。

405. Convert a Number to Hexadecimal

405. Convert a Number to Hexadecimal

405. Convert a Number to Hexadecimal

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character ''0''; otherwise, the first character in the hexadecimal string will not be the zero character.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

 

Example 1:

Input:
26

Output:
"1a"

 

Example 2:

Input:
-1

Output:
"ffffffff"

tips:

1. 将10进制化作二进制再转16进制;

2. 我觉得方法设计得比较巧妙,二进制的最低4位&15得到16进制的最低位1位;

3. 注意利用右移,是用无符号右移;

public class Solution {
  
    
    public String toHex(int num) {
        char[] map = {''0'',''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',''a'',''b'',''c'',''d'',''e'',''f''};
        if(num == 0) return "0";
        String result = "";
        while(num != 0){
            result = map[(num & 15)] + result; 
            num = (num >>> 4);
        }
        return result;
    }
}

 

关于[Algorithm] Convert a number from decimal to binary的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于"from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"、177. Convert Sorted Array to Binary Search Tree With Minimal Height【LintCode by java】、2D Convex Hulls and Extreme Points( Convex Hull Algorithms) CGAL 4.13 -User Manual、405. Convert a Number to Hexadecimal的相关信息,请在本站寻找。

本文标签: