天堂向右,我依然向左

天下之大,虽离家千里,何处不可往!何事不可为!
生活之路,纵坎坷曲折,当奋斗不息,则精彩纷呈!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

隨便寫著玩的。。。

using System;

namespace KiloNet
{
    
class  test
    {
        
static void Main(string[] args)
        {
            
//空位補零,你會選擇哪種方式?

            Console.WriteLine(
"pad('1',4)={0}",pad("1",4));
            Console.WriteLine(
"pad('12',4)={0}",pad("12",4));
            Console.WriteLine(
"pad('123',4)={0}",pad("123",4));
            Console.WriteLine(
"pad('1234',4)={0}",pad("1234",4));
            Console.WriteLine(
"pad('12345',4)={0}",pad("12345",4));
            Console.WriteLine(
"pad('123456',4)={0}",pad("123456",4));

            Console.WriteLine(
"pad2('1',4)={0}",pad2("1",4));
            Console.WriteLine(
"pad2('12',4)={0}",pad2("12",4));
            Console.WriteLine(
"pad2('123',4)={0}",pad2("123",4));
            Console.WriteLine(
"pad2('1234',4)={0}",pad2("1234",4));
            Console.WriteLine(
"pad2('12345',4)={0}",pad2("12345",4));
            Console.WriteLine(
"pad2('123456',4)={0}",pad2("123456",4));

            Console.WriteLine(
"pad3('1',4)={0}",pad3("1",4));
            Console.WriteLine(
"pad3('12',4)={0}",pad3("12",4));
            Console.WriteLine(
"pad3('123',4)={0}",pad3("123",4));
            Console.WriteLine(
"pad3('1234',4)={0}",pad3("1234",4));
            Console.WriteLine(
"pad3('12345',4)={0}",pad3("12345",4));
            Console.WriteLine(
"pad3('123456',4)={0}",pad3("123456",4));

            Console.Read();
        }

        
//正常循環
        static string pad(string num, int n) {
            
int i = num.Length;
            
while(i++ < n) num = "0" + num;
            
return num;
        }
        
        
//遞歸
        static string pad2(string num, int n) {
            
return (num.Length >= n)? num:pad2("0" + num, n);
        }

        
//一次搞定
        static string pad3(string num, int n) {
            
return ("".PadLeft(n, '0'+ num).Substring(n+ num.Length - Math.Max(num.Length, n), Math.Max(num.Length, n));
        }

    }
}
posted on 2009-09-02 16:15  老舟  阅读(323)  评论(2编辑  收藏  举报