将字符串转换为数字和放大器;反之亦然复杂性 [英] Convert string to number & vice versa complexity

查看:92
本文介绍了将字符串转换为数字和放大器;反之亦然复杂性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是一个字符串转换为等值数量的复杂性,反之亦然?它取决于编程语言的变化?

What would be the complexity of converting a string to its equivalent number or vice versa? Does it change depending on programming language?

在它的面前,需要遍历整个字符串,将其转换为一个数字,所以它的 O(N)的,或者是使用了一些类型转换?

On the face of it, one needs to traverse the entire string to convert it to a number, so it is O(n), or is some typecasting used?

这无疑出来时,我正在写一个程序来检查,如果一个给定的数字是回文与否。一种方法是将保持分裂数由基(这里10),累积的数字,并把它们一起在末端。实施例309/10 = REM(9),30/10 = REM(0),3/10 = REM(3)。我们得到903。

This doubt came about when I was writing a routine to check if a given number is a palindrome or not. One approach would be to keep dividing the number by the base (here 10), accumulate digits, and put them together at the end. Example: 309/10=rem(9), 30/10=rem(0), 3/10=rem(3). we get 903.

我把另一种方法是,这个数字转换为字符串,并自字符串有成员函数加载分裂,扭转等,code短了很多,更清洁的,但这是最好的方法做到这一点?

Another approach I took was to convert this number into a string, and since strings have loads of member functions to split, reverse etc., the code was a lot shorter and cleaner, but is this the best way to do this?

推荐答案

数字字符串的位置符号格式的数字 - 所以需要加以考虑,以转换每个数字乘以基的功率值号转换成二进制格式。

Numeric strings are numbers formatted in positional notation - so the value of each digit multiplied by a power of the base needs to be taken into account in order to convert the number into a binary format.

所以是的,这是因为运行时间的增加而线性随着越来越多的数字是增加了一个O(N)操作。然而,在实践N可以被以任何数字数据类型的语言支持(例如int32_t和的int64_t)的限制。但是,如果任意precision号码类型被使用(其中一些语言,比如Python,默认情况下使用),那么就没有限制的数字(超过可用内存显然除外)。

So yeah, it's an O(N) operation because the running time increases linearly as more digits are added. However, in practice N may be limited by whatever numeric data-types the language supports (e.g. int32_t, int64_t). But if arbitrary precision number types are used (which some languages, like Python, use by default) then there is no limit to the number of digits (other than available memory obviously).

这篇关于将字符串转换为数字和放大器;反之亦然复杂性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆