GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — LeetCode/Math/1017.Convert-to-Base--2 at master · wisdompeak/LeetCode

Expand file tree

/

1017.Convert-to-Base--2

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
/

1017.Convert-to-Base--2

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
1017.Convert-to-Base--2.cpp
1017.Convert-to-Base--2.cpp
 
 
Readme.md
Readme.md
 
 

Readme.md

1017.Convert-to-Base--2

本质上和求N的任何K进制的转化一样的做法。求得余数r=N%K作为当前最低位的数字,然后将N=(N-r)/K作为下一个循环的初始值直至为零。把所有的数字拼接起来倒序输出就是K进制的结果。

特别注意,余数r必须是正数,也就是说无法除尽的时候,采用的是向下取整。比如说(-5)/(-3),依据严格的数学定义,商是2,余数是1.

但是,当除数是负数的时候,不同语言的运算规则会不一样。在C++/Java里面,整数的除法都是向零取整。比如说(-5)/(-3),结果商是1,余数是-2.这个余数因为是负数,是无法用来作为进制转换结果的。解决方案是:将商加上一,余数加上abs(K)。这样就转变成了向下取整的结果,余数也变成了正数。在这个例子中,结果商就是2,余数是1.

事实上,在wiki里面已经明确写明了negative base calculation的方法:https://en.wikipedia.org/wiki/Negative_base#Calculation

Leetcode Link

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.