简体   繁体   中英

How to find min value of an n digit number?

I have been able to achieve what I am looking for but just want to know whether there is an inbuilt method to do so?

I have a number say 2665. Now since this is a 4 digit, I need the minimum value of a 4 digit number which is 1000.

Similarly if the number is 255, the answer would be 100.

I tried this

int len = 2665.ToString().Length;

string str = string.Empty;
for (int index = 0; index < len; index++) 
{
    if (index == 0) 
        str += "1";
    else
        str += "0";
}

This gives correct result of 1000 . But is there an inbuilt function for this?

You can use Pow and power 10 to length of string. For 1 it will give 1 for 2 it will give 10 etc.

var str = Math.Pow(10, len - 1).ToString();

您还可以使用字符串的构造函数String(Char,Int32)来创建所需的零序列。

string s = "1" + new string('0', str.Length-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM